归并排序主要的思想是分治和合并,合并我觉得挺好理解的,分治是用递归实现的感觉不太好理解,我就贴一个模板,拿着就能用了。要是像仔细学习了解归并排序的话可以看下这篇文章传送门,感觉讲的不能再详细了。。。
归并排序模板:
代码语言:javascript复制#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#define ll long long
using namespace std;
ll t[1000005];
ll a[1000005];
int n;
ll ans;
void merge(int left,int mid,int right){
int i = left, j = mid 1, k = left;
while(i <= mid && j <= right){
if(a[i] <= a[j]){
t[k ] = a[i ];
}
else{
t[k ] = a[j ];
}
}
while(i <= mid){
t[k ] = a[i ];
}
while(j <= right){
t[k ] = a[j ];
}
for(int i=left;i<=right;i ){
a[i] = t[i];
}
}
void mergesort(int left,int right){
if(left < right){
int mid = (left right) / 2;
mergesort(left,mid);
mergesort(mid 1,right);
merge(left,mid,right);
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i ){
scanf("%d",&a[i]);
}
ans = 0;
mergesort(1,n);
printf("%lldn",ans);
return 0;
}