归并排序和快速排序的区别:
1.分区间时,快排按照值来分,归排按照下标来分
2.快排先处理当前区间,再递归处理子区间;归排先递归处理子区间,再处理当前区间
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 cnt=0;
int i=l,j=mid+1;
while(i<=mid && j<=r)
{
if(q[i]<q[j])t[cnt++]=q[i++];
else t[cnt++]=q[j++];
}
while(j<=r)t[cnt++]=q[j++];
while(i<=mid)t[cnt++]=q[i++];
for(int i=l,j=0;i<=r;i++,j++)q[i]=t[j];
}
int main()
{
cin>>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]);
}
return 0;
}
可以用到归并排序的变体题型:求逆序对的个数
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
typedef long long LL;
int q[N],t[N];
int n;
LL merge_sort(int l,int r)
{
if(l==r)return 0;
int mid = l+r>>1;
LL res = merge_sort(l,mid)+merge_sort(mid+1,r);
int k=0,i=l,j=mid+1;
while(i<=mid && j<=r)
{
if(q[j]>=q[i])t[k++]=q[i++];
else{
t[k++]=q[j++];
res += mid-i+1;
}
}
while(i<=mid)t[k++]=q[i++];
while(j<=r)t[k++]=q[j++];
for(int i=l,j=0;i<=r;i++,j++)q[i]=t[j];
return res;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
scanf("%d",&q[i]);
}
cout<<merge_sort(0,n-1)<<endl;
return 0;
}