【归并排序代码】
#include <bits/stdc++.h>
using namespace std;
const int maxn=100005;
int a[maxn];
int t[maxn];
long long ans;
void merge_sort(int low,int high) {
if(low>=high) return; //"low>=high" equivalent to "low==high"
int mid=(low+high)>>1;
merge_sort(low,mid);
merge_sort(mid+1,high);
for(int i=low; i<=high; i++) t[i]=a[i];
int ls=low,hs=mid+1; //ls:low half interval's starting, hs:high half interval's starting
for(int i=low; i<=high; i++) {
if(ls>mid) a[i]=t[hs++];
else if(hs>high) a[i]=t[ls++];
else if(t[ls]<=t[hs]) a[i]=t[ls++];
else {
if(t[ls]>t[hs]) {
//ans+=mid-ls+1;
a[i]=t[hs++];
}
}
}
}
int main() {
int n;
cin>>n;
for(int i=1; i<=n; i++) cin>>a[i];
merge_sort(1,n);
for(int i=1; i<=n; i++) cout<<a[i]<<" ";
//cout<<ans;
return 0;
}
/*
in:
6
2 3 4 5 6 1
out:
1 2 3 4 5 6
in:
9
8 4 5 7 1 3 6 2 9
out:
1 2 3 4 5 6 7 8 9
*/
【归并排序模拟执行示意图】
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/119768122