【归并排序算法代码】
下文源代码是归并排序的一种实现方法。若去掉其中的第26行语句 ans+=mid-ls+1; 及第42行语句 cout<<ans; 前的注释,并在第40行语句 for(int i=1; i<=n; i++) cout<<a[i]<<" "; 前添加注释之后,便成为求逆序对的代码。
#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/qionggaobi9328/article/details/105676962
https://blog.csdn.net/zpznba/article/details/88395447
https://blog.csdn.net/zpznba/article/details/83745205
https://blog.csdn.net/kevinmeanscool/article/details/87916085
https://blog.csdn.net/hnjzsyjyj/article/details/119767480