各种排序代码集合笔记 发表于 2015年09月03日 | 分类于 算法 | 字数 3,220 | 阅读次数 各种排序代码集合 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154#include<stdio.h>//直接插入排序void InsertSort(int *datatemp,int n){ int *data = new int[n]; for(int i=0;i<n;i++){ data[i]=datatemp[i]; } int temp,j; for(int i=2;i<n;i++){ temp = data[i]; if(data[i]<data[i-1]){ j = i-1; while(data[j]>temp){ data[j+1]=data[j]; j--; } data[j+1]=temp; } } //输出 printf("直接插入排序:\t"); for(int i=1;i<n;i++){ printf("%d ",data[i]); } printf("\n");}//希尔排序void ShellSort(int *datatemp,int n){ int *data = new int[n]; for(int i=0;i<n;i++){ data[i]=datatemp[i]; } int dk = n/2; while(dk>=1){ //插入排序了下面是 for(int i=dk;i<n;i+=dk){ int temp = data[i]; if(data[i]<data[i-dk]){ int j = i-dk; while(data[j]>temp){ data[j+dk]=data[j]; j-=dk; } data[j+dk]=temp; } } dk/=2; } //输出 printf("希尔排序:\t"); for(int i=1;i<n;i++){ printf("%d ",data[i]); } printf("\n");}//快速排序int QsortThird(int low,int high ,int *data){ int temp = data[low]; while(low<high){ while(low<high && data[high]>=temp)high--; data[low]=data[high]; while(data[low]<=temp && low<high) low++; data[high]=data[low]; } data[low]=temp; return low;}void QsortSecond(int low,int high ,int *data){ if(low<high){ int mid = QsortThird(low,high,data); QsortSecond(low,mid-1,data); QsortSecond(mid+1,high,data); }}void QsortFrist(int *datatemp,int n){ int *data = new int[n]; for(int i=0;i<n;i++){ data[i]=datatemp[i]; } QsortSecond(1,n-1,data); //输出 printf("快速排序:\t"); for(int i=1;i<n;i++){ printf("%d ",data[i]); } printf("\n");}//归并排序void Merge(int *A,int low,int mid,int high,int *B){ int x=low,m=mid,y=mid+1,n=high; int k=0; while(x<=m && y<=n){ if (A[x] <= A[y]) B[k++]=A[x++]; else B[k++]=A[y++]; } while(x<=m){ B[k++]=A[x++]; } while(y<=n){ B[k++]=A[y++]; } //把已经有序的序列再返回 for (int i = 0; i < k; i++) A[low+i] = B[i]; }void MergeSortSecond(int *A,int low,int high,int *B){ if(low<high){ int mid = (low+high)/2; MergeSortSecond(A,low,mid,B); MergeSortSecond(A,mid+1,high,B); Merge(A,low, mid, high, B); }}void MergeSortFirst(int *datatemp,int n){ int *data = new int[n]; for(int i=0;i<n;i++){ data[i]=datatemp[i]; } int *datatmp = new int[n]; MergeSortSecond(data,1,n-1,datatmp); //输出 printf("归并排序:\t"); for(int i=1;i<n;i++){ printf("%d ",data[i]); } printf("\n");}//堆排序void HeapSort(){}int main(){ int data[8]={0,49,38,65,97,76,13,27};//后七个数是数据,第一个是哨兵,这里为了做例子才这么写 //输出 printf("原始数据:\t"); for(int i=1;i<8;i++){ printf("%d ",data[i]); } printf("\n"); InsertSort(data,8); ShellSort(data,8); QsortFrist(data,8); MergeSortFirst(data,8); return 0;} 还没写完,有空把堆排序补上。 扫一扫,用手机看更方便~ 坚持原创技术分享,您的支持将鼓励我继续创作! 赏 微信打赏 支付宝打赏