You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
//归并排序
void copyArray(int source[], int dest[],int len,int first)
{
int i;
int j=first;
for(i=0;i<len;i++)
{
dest[j] = source[i];
j++;
}
}
//相邻两个有序子序列的归并函数, 将a[low...mid]和a[mid+1...high]归并到T[LOW..high]中
void merge(int a[],int left,int right)
{
int begin1 = left;
int mid = (left+right)/2 ;
int begin2 = mid+1;
int k=0;
int newArrayLen = right-left+1;
int *b = (int*)malloc(newArrayLen*sizeof(int));
while(begin1<=mid && begin2<=right)
{
if(a[begin1]<=a[begin2])
b[k++] = a[begin1++];
else
b[k++] = a[begin2++];
}
while(begin1<=mid)
b[k++] = a[begin1++];
while(begin2<=right)
b[k++] = a[begin2++];
copyArray(b,a,newArrayLen,left);
free(b);
}
//归并函数,将a[low...high]归并到T[low...high]中
void mergeSort(int a[],int left,int right)
{
int i;
// 保证至少有两个元素
if(left < right)
{
i = (left+right)/2;
mergeSort(a,left,i);
mergeSort(a,i+1,right);
merge(a,left,right);
}
}
void MergeSort(int a[],int n)
{
mergeSort(a,0,n-1);
}
int main()
{
int n;
cin>>n;
int *a=new int[n];
for(int j=0;j<n;j++)
cin>>a[j];
MergeSort(a,n);
for(int i=0;i<n;i++)
cout<<a[i];
delete []a;
}