#include<iostream>
using namespace std;
int length(int a[])
{
int i;
for(i=0;a[i]!='\0';i++);
return i;
}
void copy1(int a[],int b[],int l,int r)
{
for(int i=l;i<=r;i++)
a[i]=b[i];
}
//将数组排序并合并到标数组中,调用copy1函数将b数组赋值给a
void merge1(int a[],int b[],int l,int m,int r)
{
int i=l,j=m+1,n=l;
while((i<=m)&&(j<=r))
{
if(a[i]<a[j])
{
b[n++]=a[i++];
}
else
{
b[n++]=a[j++];
}
}
if(i>m)
{
for(int t=j;t<=r;t++)
b[n++]=a[t];
}
else
{
for(int t=i;t<=m;t++)
b[n++]=a[t];
}
copy1(a,b,l,r);
}
//将数组分割
void mergeSort(int a[],int left,int right)
{
int mid;
int b[length(a)];
if(left<right)
{
mid =(left+right)/2;
mergeSort(a,left,mid);
mergeSort(a,mid+1,right);
merge1(a,b,left,mid,right);
}
}
int main()
{
int i,n;
cout<<"请输入数组元素的个数:"<<endl;
cin>>n;
int *a=new int(n);
cout<<"请输入数组元素:"<<endl;
for( i = 0 ; i < n ; i++ )
cin>>a[i];
mergeSort(a,0,n-1);
cout<<"归并排序后,数组元素输出为:";
for(int g=0;g<n;g++)
cout<<a[g]<<" ";
return 0;
}
//实验结果: