c++实现的一些排序算法
最近用c++简单实现了一些排序算法,记下来,以便以后用到//合并排序全代码void merge (int a[], int low, int high){ int i, j, k = -1; for (i=low, j=(low+high)/2+1; i<=(low+high)/2||j<=high; ){ if ( i>(low+high)/2 ) { b[++k]=a; } else if (j>high) { b[++k]=a; } else if (a>=a) { b[++k]=a; } else b[++k]=a;} k=0; for(i=low; i<=high; i++) { a=b; }} void mergeSort(int a[], int low, int high){ if ( high > low){ mergeSort(a, low, (low+high)/2); mergeSort(a, 1+(low+high)/2, high); merge(a, low, high);}}//直接插入排序void insertSort(double a[],int n){int i,j;double k;for(i=1;i<n;i++){ if(a<a){k=a;for(j=i-1;a>k && j>=0;j--)a=a;a=k;}}}//折半插入排序void binsertSort(double a[],int n){ int i,j,m,low,high; double k; for(i=1;i<n;i++) { k=a; low=0; high=i-1; while(low<=high){ m=(low+high)/2; if(k<a) high=m-1; else low=m+1;}for(j=i-1;j>=high && j>=0;j--)a=a; a=k; } }//快速排序//分割函数int Partition(doublea[],int n,int low,int high){double k=a;while(low<high){ while(low<high && a>=k)--high;a=a;while(low<high && a<=k)++low;a=a;}a=k;return low;}void quitSort(double a[],int n,int low,int high){int key;if(low<high){ key=Partition(a,n,low,high);quitSort(a,n,low,key-1); quitSort(a,n,key+1,high);}}//堆排序//筛选算法void sift(double a[],int k,int m){ int i=k,j=i*2;while(j<=m-1){ if(j<m && a<a)j++; if(a<a) { double temp=a;a=a;a=temp;i=j;j=i*2; } else break;}}void heapSort(double a[],int n){ int k=(n-1)/2; for(int i=k;i>=1;i--) sift(a,i,n-1); for(int j=n-1;j>1;j--) { double temp=a;a=a;a=temp;sift(a,1,j-1); }}int main(){int i;double a={23,56,12,3,58,62,18,36,18};double b={23,56,12,3,58,62,18,36,18};double c={23,56,12,3,58,62,18,36,18};int d={23,56,12,3,58,62,18,36,18};double e={0,23,56,12,3,58,62,18,36,18};cout<<"直接插入排序";insertSort(a,9);for(i=0;i<9;i++)cout<<a<<"";cout<<endl;cout<<"折半插入排序"; binsertSort(b,9);for(i=0;i<9;i++)cout<<b<<"";cout<<endl;cout<<"合并排序";mergeSort(d,0,8);for(i=0;i<9;i++)cout<<d<<"";cout<<endl;cout<<"快速排序";quitSort(c,9,0,8);for(i=0;i<9;i++)cout<<c<<"";cout<<endl;cout<<"堆排序";heapSort(e,10);for(i=0;i<10;i++)cout<<e<<"";return 0;}
结果
public static void sort(int[] array,int size) { int i,j,temp; for(i=0;i<size;i++) { for(j=0;j<size-i-1;j++) { if(array>array) { temp = array; array = array; array = temp; } System.out.println(Arrays.toString(array)); } System.out.println("第"+i+"次----------------------"); } }
页:
[1]