前言
各种排序算法的实现,这东西,几天不写,就略感手生,需要定期不断温习,各种排序算法的思想都很清晰,写的过程中需要额外注意边界情况,递归结束条件,各种边界判断条件。没事写写,温故而知新。
手写排序算法
选择排序
|
|
冒泡排序
|
|
直接插入排序
|
|
希尔排序
|
|
归并排序
递归版本
123456789101112131415161718192021222324//递归归并排序struct MergeSort{ //稳定static void Merge_sort(int a[],int low,int high,int aux[]){ //将[low,high]进行归并if(high<=low) return;int mid = low + (high-low)/2;Merge_sort(a,low,mid,aux);Merge_sort(a,mid+1,high,aux);Merge(a,low,mid,high,aux);}static void Merge(int a[],int low,int mid,int high,int aux[]){ //将[low,mid] 与 [mid+1,high]进行归并int i = low;int j = mid + 1;int index = low;while(i<=mid&&j<=high){if(a[i]<a[j]) aux[index++] = a[i++];else aux[index++] = a[j++];}while(i<=mid) aux[index++] = a[i++];while(j<=high) aux[index++] = a[j++];for(int k=low;k<=high;++k){a[k] = aux[k];}}};非递归版本
12345678910111213141516171819202122232425//非递归归并排序struct NoRecMergeSort{ //稳定static norecMergeSort(int a[],int length,int aux[]){cout<<"norecMergeSort"<<endl;for(int sz = 1;sz<length;sz=sz+sz){for(int lo = 0;lo<length-sz;lo+=sz+sz){ //lo = lo + sz + szMerge(a,lo,lo+sz-1,min(lo+sz+sz-1,length-1),aux); // lo lo+sz-1 min(lo+sz+sz-1,length-1)}}}static void Merge(int a[],int low,int mid,int high,int aux[]){ //将[low,mid] 与 [mid+1,high]进行归并int i = low;int j = mid + 1;int index = low;while(i<=mid&&j<=high){if(a[i]<a[j]) aux[index++] = a[i++];else aux[index++] = a[j++];}while(i<=mid) aux[index++] = a[i++];while(j<=high) aux[index++] = a[j++];for(int k=low;k<=high;++k){a[k] = aux[k];}}};
快速排序
|
|
堆排序
|
|
完整程序示例
|
|