#include<iostream>
using namespace std;
void Merge(int a[],int b[],int first,int mid,int last)//合并两个有序数组
{
int p=first,q=mid+1;
int pos=first;
while(p<=mid&&q<=last)
{
if(a[p]<a[q])
{
b[pos++]=a[p++];
}
else
{
b[pos++]=a[q++];
}
}
if(p<=mid)
{
while(p<=mid)
{
b[pos++]=a[p++];
}
}
else
{
while(q<=last)
{
b[pos++]=a[q++];
}
}
}
void Merge_pass(int a[],int b[],int gap,int n)//合并指定步长的两个数组
{
int i=0;
int j=0;
while(i<=n-2*gap+1)
{
Merge(a,b,i,i+gap-1,i+gap*2-1);
i=i+gap*2;
}
if(i<(n-gap))//剩的数据多于一个步长,少于两个步长
Merge(a,b,i,i+gap-1,n-1);
else
for(j=i;j<n;j++)
{
b[j]=a[j];
}
}
void Merge_sort(int a[],int b[],int n)//非递归 不回写
{
int gap=1;
while(gap<n)
{
Merge_pass(a,b,gap,n);//a b和b a交替
gap=gap*2;
Merge_pass(b,a,gap,n);
gap=gap*2;
}
}
int main()
{
int a[10]={9,2,3,7,1,8,4,6,5,0};
int b[10];
Merge_sort(a,b,10);
for(int i=0;i<10;i++)
cout<<a[i]<<endl;
system("pause");
return 0;
}