#include <iostream> //合并排序非递归--自然合并排序 typedef int Type; using namespace std; void Merge(Type c[],Type d[],int l,int m,int r){ //合并c[l:m] c[m+1:r] 到 d[l:r] int i=l,j=m+1,k=l; while( (i<=m)&&(j<=r)) if(c[i]<=c[j]) d[k++]=c[i++]; else d[k++]=c[j++]; if(i>m) for(int q=j;q<=r;q++) d[k++]=c[q]; else for(int q=i;q<=m;q++) d[k++]=c[q]; } void MergePass(Type x[],Type y[],int s,int n){ //合并大小为s的相邻子数组 int i=0; while(i<=n-2*s){ Merge(x,y,i,i+s-1,i+2*s-1); i=i+s*2; } if(i+s<n) Merge(x,y,i,i+s-1,n-1); else for(int j=i;j<=n-1;j++) y[j]=x[j]; } void MergeSort(Type a[],int n){ int s=1; Type *b=new Type [n]; while(s<n){ MergePass(a,b,s,n);//合并到数组b s+=s; MergePass(b,a,s,n);// 合并到数组a s+=s; } } int main() { int p[]={4,8,3,7,1,5,6,2}; MergeSort(p,8); for(int i=0;i<=7;i++) cout<<p[i]<<","; return 0; }