核心:
void merge(int a[],int l,int r){
if(l>=r) return;
int mid = l+r>>1;
merge(a,l,mid);//先递归再归并
merge(a,mid+1,r);
int t=0;
//左右半段的起点
int i=l,j=mid+1;
while(i <= mid && j <= r){
if(a[i] <= a[j]) res[t++] = a[i++];
else res[t++] = a[j++];
}
//如果还有剩余
while(i<=mid){
res[t++] = a[i++];
}
while(j<=r){
res[t++] = a[j++];
}
//先左再右,每一次排好序的都是左半段
for(int i=l,j=0;i<=r;i++,j++){
a[i] = res[j];//为什么呢
}
}
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
#include<cmath>
using namespace std;
int n;
int a[1000];
int res[1000];
void merge(int a[],int l,int r){
if(l>=r) return;
int mid = l+r>>1;
merge(a,l,mid);//先递归再归并
merge(a,mid+1,r);
int t=0;
//左右半段的起点
int i=l,j=mid+1;
while(i <= mid && j <= r){
if(a[i] <= a[j]) res[t++] = a[i++];
else res[t++] = a[j++];
}
//如果还有剩余
while(i<=mid){
res[t++] = a[i++];
}
while(j<=r){
res[t++] = a[j++];
}
for(int i=l,j=0;i<=r;i++,j++){
a[i] = res[j];//为什么呢
}
}
int main()
{
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
merge(a,0,n-1);
for(int i=0;i<n;i++){
cout<<a[i]<<' ';
}
return 0;
}