#include <iostream>
using namespace std;
const int N=1e6+10;
int n;
int q[N],tmp[N];//tmp暂存有序数组
void merge_sort(int q[],int l, int r){
if(l>=r)return;
int mid=(l+r)>>1;
merge_sort(q,l,mid),merge_sort(q,mid+1,r);//分段
int k=0,i=l,j=mid+1;
while(i<=mid && j<=r){
if(q[i]<=q[j]) tmp[k++]=q[i++];//两段中依次取较小的数加入tmp数组;
else tmp[k++]=q[j++];
}
while(i<=mid)tmp[k++]=q[i++];//若第一段有剩余
while(j<=r)tmp[k++]=q[j++];//若第二段有剩余
for(int i=l,j=0;i<=r;i++,j++)q[i]=tmp[j];//赋值给原数组,注意此处i范围:[l,r]
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&q[i]);
merge_sort(q,0,n-1);
for(int i=0;i<n;i++) printf("%d ",q[i]);
}
acwing787.归并排序
于 2024-02-14 18:48:25 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)