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));}