|
|
最近用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[j++]; } else if (j>high) { b[++k]=a[i++]; } else if (a>=a[j]) { b[++k]=a[j++]; } else b[++k]=a[i++];} k=0; for(i=low; i<=high; i++) { a=b[k++]; }} 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[i-1]){k=a;for(j=i-1;a[j]>k && j>=0;j--)a[j+1]=a[j];a[j+1]=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[m]) high=m-1; else low=m+1; } for(j=i-1;j>=high && j>=0;j--)a[j+1]=a[j]; a[high+1]=k; } }//快速排序//分割函数int Partition(double a[],int n,int low,int high){ double k=a[low]; while(low<high) { while(low<high && a[high]>=k)--high;a[low]=a[high];while(low<high && a[low]<=k)++low;a[high]=a[low]; } a[low]=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[j]<a[j+1])j++; if(a<a[j]) { double temp=a; a=a[j]; a[j]=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[1]; a[1]=a[j]; a[j]=temp; sift(a,1,j-1); }}int main(){int i;double a[9]={23,56,12,3,58,62,18,36,18};double b[9]={23,56,12,3,58,62,18,36,18};double c[9]={23,56,12,3,58,62,18,36,18};int d[9]={23,56,12,3,58,62,18,36,18};double e[10]={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;}
结果[img]
[/img]
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[j]>array[j+1]) { temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } System.out.println(Arrays.toString(array)); } System.out.println("第"+i+"次----------------------"); } } |
|