一日一码03——插入排序

来源:互联网 发布:北航大数据在职研究生 编辑:程序博客网 时间:2024/06/03 19:39

把基本排序都补全吧。


插入排序


//插入排序2013/09/08#include <stdio.h>#include <stdlib.h>#include <time.h>#include <malloc.h>//范例程序,从后往前比较,比较和移位一次循环就够了,精妙!void insertSort(int* a, int n){int i,j,tmp;for( i = 1; i < n; i++){tmp = a[i];j = i - 1;while( j >= 0 && tmp < a[j]){//我错写成过 j > 0a[j+1] = a[j];j--;}a[j+1] = tmp;//我错写成过 a[j - 1] = tmp;}}//鄙人拙作,从前向后比较,比较和移位分别用2次循环,麻烦!//有一次运行结果不对,现在都没查出原因,谁看出来请斧正!void insertSort_my(int* a, int n){int i,j,tmp,pos;for ( i = 0 ; i < n ; i++){//哨兵tmp = a[i];pos = 0;//寻找插入位置for ( j = 0 ; j < i - 1; j++ ){if(tmp <= a[0]){pos = 0;break;}if(tmp >= a[i - 1]){pos = i;break;}if(tmp >= a[j] && tmp < a[j+1]){pos = j+1;break;}}//比哨兵大的元素后移for( j = i; j > pos; j--){a[j] = a[j-1];}//插入到正确位置a[pos] = tmp;}}void initArr(int* a, int n){int i;srand(time(NULL));for(i = 0; i < n; i++){a[i] =  rand()%100;}}void printArr(int* a, int n){int i;for (i = 0;i < n; i++){printf("%d,",a[i]);}printf("\n");}void main(){int* arr;int n;printf("Input the size of array:");scanf("%d",&n);arr = (int *)malloc(n*sizeof(int));initArr(arr,n);printArr(arr,n);insertSort(arr,n);printArr(arr,n);}


原创粉丝点击