voidPrintArray(int* a,int n){for(size_t i =0; i < n;++i){printf("%d ", a[i]);}printf("\n");}voidInsertSort(int* a,int n){// 控制end的位置从0走到n-2for(int i =0; i < n -1;++i){// 单趟排序// 在[0,end]区间中插入tmp,依旧有序int end = i;int tmp = a[end +1];while(end >=0){if(a[end]> tmp){
a[end +1]= a[end];--end;}else{break;}}
a[end +1]= tmp;}}voidTestInsertSort(){int a[]={3,6,2,5,7,9,8,6,1,4};InsertSort(a,sizeof(a)/sizeof(int));PrintArray(a,sizeof(a)/sizeof(int));}
希尔排序
// 平均时间复杂度:O(N^1.3) 什么情况下最坏:顺序有序(预排序全部白做了,还不如直接插入排序)voidShellSort(int* a,int n){// gap > 1时为预排序 接近有序// gap == 1时为直接插入排序 有序int gap = n;while(gap >1){// 间隔为gap的预排序
gap = gap /3+1;// +1是保证最后一次一定是1for(int i =0; i < n - gap;++i){int end = i;int tmp = a[end + gap];while(end >=0){if(a[end]> tmp){
a[end + gap]= a[end];
end -= gap;}else{break;}}
a[end + gap]= tmp;}}}voidTestShellSort(){int a[]={3,6,2,5,7,9,8,6,1,4};ShellSort(a,sizeof(a)/sizeof(int));PrintArray(a,sizeof(a)/sizeof(int));}
选择排序
voidSwap(int* p1,int* p2){int tmp =*p1;*p1 =*p2;*p2 = tmp;}// 时间复杂度 O(N*N)voidSelectSort(int* a,int n){int begin =0, end = n -1;while(begin < end){// [begin, end] 选出一个最小的,选出一个最大的下标int mini = begin, maxi = end;for(int i = begin; i <= end;++i){if(a[i]> a[maxi])
maxi = i;if(a[i]< a[mini])
mini = i;}Swap(&a[begin],&a[mini]);// 修正if(begin == maxi)
maxi = mini;Swap(&a[end],&a[maxi]);//printf("[%d,%d]", begin, end);//PrintArray(a, n);++begin;--end;}}voidTestSelectSort(){int a[]={3,6,2,5,7,9,8,6,1,4};// int a[] = { 9, 6, 2, 5, 7, 3, 8, 6, 1, 4 };SelectSort(a,sizeof(a)/sizeof(int));PrintArray(a,sizeof(a)/sizeof(int));}
堆排序
voidAdjustDwon(int* a,int n,int root){int parent = root;int child = parent *2+1;while(child < n){// 选出左右孩子中大的那一个if(child+1< n && a[child+1]> a[child]){++child;}// 1、如果孩纸比父亲大,交换,继续向下调整// 2、如果孩纸小于父亲,则调整结束if(a[child]> a[parent]){Swap(&a[child],&a[parent]);
parent = child;
child = parent *2+1;}else{break;}}}// O(N*LogN)voidHeapSort(int* a,int n){// 排升序,建大堆// O(N)for(int i =(n-1-1)/2; i >=0;--i){AdjustDwon(a, n, i);}int end = n -1;while(end >0){// 把堆顶当前最大数一次换到最后Swap(&a[0],&a[end]);// 调堆选出剩下的数当中最大AdjustDwon(a, end,0);--end;}}voidTestHeapSort(){int a[]={3,6,2,5,7,9,8,6,1,4};// int a[] = { 9, 6, 2, 5, 7, 3, 8, 6, 1, 4 };HeapSort(a,sizeof(a)/sizeof(int));PrintArray(a,sizeof(a)/sizeof(int));}
冒泡排序
voidBubbleSort(int* a,int n){// 单趟排序for(int end = n -1; end >0;--end){int flag =0;for(int i =0; i < end;++i){if(a[i]> a[i +1]){Swap(&a[i],&a[i +1]);
flag =1;}}if(flag ==0){break;}}}voidTestBubbleSort(){int a[]={3,6,2,5,7,9,8,6,1,4};// int a[] = { 9, 6, 2, 5, 7, 3, 8, 6, 1, 4 };BubbleSort(a,sizeof(a)/sizeof(int));PrintArray(a,sizeof(a)/sizeof(int));}