归并排序
运用分治,将二分之n进行排序后再合成
#include<iostream>
using namespace std;
int num[1005];
void merge(int low,int mid,int high) {
int a[1005],res=0,i=low,j=mid+1;
while(i<=mid&&j<=high) {
if(num[i]<num[j]) a[res]=num[i],res++,i++;
else a[res]=num[j],res++,j++;
}
while(i<=mid) a[res]=num[i],res++,i++;
while(j<=high) a[res]=num[j],res++,j++;
for(i=0;i<res;i++) {
num[low+i]=a[i];
}
}
void Sort(int low,int high) {
if(low>=high) return;
int mid=(low+high)/2;
Sort(low,mid);
Sort(mid+1,high);
merge(low,mid,high);
}
int main() {
int n;
cin>>n;
for(int i=1;i<=n;i++) {
cin>>num[i];
}
Sort(1,n);
for(int i=1;i<=n;i++) {
cout<<num[i]<<" ";
}
}