归并
排序是建立在归并操作上的一种有效的
排序算法。该算法是采用
分治法(Divide and Conquer)的一个非常典型的应用。值得注意的是归并排序是一种
稳定的排序方法。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。
#include <iostream>
#include <cstdio>
using namespace std;
const int INF=1e5;
int num[INF];
void Mergesort(int first,int mid,int last) //将分治得到的两个序列排序 合并
{
int *temp=new int[last-first+2];
int i=first;
int m=mid;
int j=mid+1;
int n=last;
int k(0);
while(i<=m && j<=n)
{
if(num[i]<num[j])
temp[k++]=num[i++];
else temp[k++]=num[j++];
}
while(i<=m)
temp[k++]=num[i++];
while(j<=n)
temp[k++]=num[j++];
for(int i=0;i<k;i++)
num[first+i]=temp[i];
delete []temp;
}
void Merge(int first,int last) //利用分治的思想将原序列分开
{
if(first<last)
{
int mid=(first+last)/2;
Merge(first,mid);
Merge(mid+1,last);
Mergesort(first,mid,last);
}
}
int main()
{
int ncase;
cin>>ncase;
while(ncase--)
{
int n;
cin>>n;
for(int i=0;i<n;i++)
scanf("%d",&num[i]);
Merge(0,n-1);
for(int i=0;i<n;i++)
printf("%d ",num[i]);
cout<<endl;
}
return 0;
}