本博客参考常用排序算法总结(一)
#include <iostream> using namespace std; void chooseSort(int ff[],int n){ for(int i=0;i<n;i++){ int min = i;//index of min number //find min index--------time for(int j=i+1;j<n;j++){ if(ff[min]>ff[j]){ min = j; } } //exchange ff[i] and ff[min]-----memory and time int temp = ff[i]; ff[i] = ff[min]; ff[min] = temp; } } void insertSort(int ff[],int n){ for (int i = 1; i < n; i++) { for (int j = i; j > 0; j--) { if(ff[j]<ff[j-1]){ int temp = ff[j]; ff[j] = ff[j-1]; ff[j-1] = temp; } } } } void insertDichotomySort(int ff[],int n){ for(int i=1;i<n;i++){ int get = ff[i];//sorted number int left = 0; int right = i-1; while (left <= right) { int middle = (left+right)/2; if(get<ff[middle]){ right = middle-1; }else{ left = middle+1; } } for(int j=i-1;j>=left;j--){ ff[j+1] = ff[j]; } ff[left] = get; } } void shellSort(int ff[], int n){ int h=0; while(h<=n){ h=3*h+1;//increment } while(h>=1){ for(int i=h;i<n;i++){//insert sort int get = ff[i]; int j= i-h; while(j>=0&&get<ff[j]){ ff[j+h] = ff[j]; j=j-h; } ff[j+h] = get; } h = (h-1)/3;//decline } } void Merge(int ff[],int left,int mid,int right){ int len = right-left+1; int *temp = new int[len];// 辅助空间O(n) int index = 0; int i = left;// 前一组数的起始元素 int j = mid+1;// 后一组数的起始元素 while(i<=mid&&j<=right){ temp[index++] = ff[i]<=ff[j]?ff[i++]:ff[j++];//=保证归并排序的稳定性 } //把末尾数加上 while (i <= mid) { temp[index++] = ff[i++]; } while (j <= right) { temp[index++] = ff[j++]; } //把排序后的temp赋值回原数组 for (int k = 0; k < len; k++) { ff[left++] = temp[k]; } } //归并排序的递归实现,自顶向下 void mergeSortRecursion(int ff[],int left,int right){ if (left == right) { return; } int mid = (left+right)/2; mergeSortRecursion(ff,left,mid); mergeSortRecursion(ff, mid + 1, right); Merge(ff, left, mid, right); } //归并排序的非递归实现,自下向顶 void mergeSortIteration(int ff[],int len){ int left,mid,right; for (int i = 1; i < len; i *= 2) { left = 0; while (left + i < len) { mid = left+i-1; right = mid+i<len?mid+i:len-1; Merge(ff, left, mid, right); left = right+1; } } } //quick sort int partition(int ff[],int left,int right){ int pivot = ff[right];//选择最后一个数作为基准数 int blank = right;//填坑法 while(left<right){ //从左边找到第一个大于pivot的,放到后面的坑里 while(left<right&&ff[left]<=pivot){ left++; } ff[blank] = ff[left]; blank = left; //从右边找到第一个小于pivot的,放到前面的坑里 while(left<right&&ff[right]>=pivot){ right--; } ff[blank] = ff[right]; blank = right; } //最后剩的那个坑放pivot ff[blank] = pivot; return blank; } void quickSort(int ff[],int left,int right){ if(left>=right){ return; } int index = partition(ff, left, right); quickSort(ff,left,index-1); quickSort(ff, index+1, right); } int main() { int f[100]={3,1,6,5,8,2,0,7,4}; quickSort(f,0,8); for(int i=0;i<9;i++){ cout<<f[i]<<" "; } cout<<endl; }