快速排序 & 归并排序模板
快速排序+随机化:
#include<bits/stdc++.h>
#define Rand(a,b) rand()%(b-a)+a
using namespace std;
const int maxn=200010;
int a[maxn];
int read(){
int Value=0,Base=1;char Ch=getchar();
for(;!isdigit(Ch);Ch=getchar())if(Ch=='-')Base=-1;
for(;isdigit(Ch);Ch=getchar())Value=Value*10+(Ch^'0');
return Value*Base;
}
void Quick_sort(int l,int r){
if(l>=r)return ;
int key=a[Rand(l,r)],head=l,tail=r;
while(head<=tail){
while(a[head]<key)head++;
while(a[tail]>key)tail--;
if(head<=tail)
swap(a[head++],a[tail--]);
}
Quick_sort(l,tail);Quick_sort(head,r);
}
int main( ){
int m,n,j,k,i;
srand((int)time(NULL));
n=read();
for(i=1;i<=n;i++)
a[i]=read();
Quick_sort(1,n);
for(i=1;i<=n;i++)
printf("%d ",a[i]);
puts("");
return 0;
}
归并排序+逆序对:
#include<bits/stdc++.h>
using namespace std;
const int maxn=200010;
int a[maxn],ans,t[maxn];
int read(){
int Value=0,Base=1;char Ch=getchar();
for(;!isdigit(Ch);Ch=getchar())if(Ch=='-')Base=-1;
for(;isdigit(Ch);Ch=getchar())Value=Value*10+(Ch^'0');
return Value*Base;
}
void Merge_sort(int l,int r){
if(l>=r)return ;
int mid=(l+r)>>1,i=l,j=mid+1,k=l;
Merge_sort(l,mid);Merge_sort(mid+1,r);
while(i<=mid && j<=r){
if(a[i]<=a[j])t[k++]=a[i++];
else t[k++]=a[j++],ans+=mid-i+1;
}
while(i<=mid)t[k++]=a[i++];
while(j<=r)t[k++]=a[j++];
for(i=l;i<=r;i++)a[i]=t[i];
}
int main( ){
int m,n,j,k,i;
n=read();
for(i=1;i<=n;i++)a[i]=read();
Merge_sort(1,n);
printf("%d\n",ans);
/*
for(i=1;i<=n;i++)
printf("%d ",a[i]);
puts("");
*/
return 0;
}
思路比较简单,都是分治法的体现,可进行比较