算法竞赛模板 归并排序
ps:数组下标从0开始哦!
①求逆序对个数的归并排序
int tmp[MAX],rec[MAX]; int sum;//求逆序对个数 void merge(int low,int mid,int high) { int i=low,j=mid+1,k=low; while(i<=mid&&j<=high) { if(rec[i]<=rec[j]) tmp[k++]=rec[i++]; else { tmp[k++]=rec[j++]; sum+=mid-i+1; } } while(i<=mid) tmp[k++]=rec[i++]; while(j<=high) tmp[k++]=rec[j++]; for(i=low;i<=high;i++) rec[i]=tmp[i]; } void mergesort(int low,int high) { if(low<high) { int mid=(low+high)/2; mergesort(low,mid); mergesort(mid+1,high); merge(low,mid,high); } } int main() { int n; while(scanf("%d",&n)!=EOF,n) { int i; for(i=0;i<n;i++) scanf("%d",&rec[i]); sum=0; mergesort(0,n-1); printf("%d\n",sum); } return 0; }
②纯归并排序
int tmp[MAX],rec[MAX]; void merge(int low,int mid,int high) { int i=low,j=mid+1,k=low; while(i<=mid&&j<=high) { if(rec[i]<=rec[j]) tmp[k++]=rec[i++]; else tmp[k++]=rec[j++]; } while(i<=mid) tmp[k++]=rec[i++]; while(j<=high) tmp[k++]=rec[j++]; for(i=low;i<=high;i++) rec[i]=tmp[i]; } void mergesort(int low,int high) { if(low<high) { int mid=(low+high)/2; mergesort(low,mid); mergesort(mid+1,high); merge(low,mid,high); } }