归并排序
归并排序本质上是分治法,就是在递归回溯回来的时候把数组排好序。
void MergeSort1(int *a, int p, int r){
if (p<r){
int q = (p+r)/2;
MergeSort1(a, p, q);
MergeSort1(a, q+1, r);
int n1 = q-p+1;
int n2 = r-q;
int *L = new int[n1+1];
int *R = new int[n2+1];
int i, j, k;
for (i=0; i<n1; i++)L[i] = a[p+i];
for (j=0; j<n2; j++)R[j] = a[q+j+1];
L[n1] = 10000000; //保证把剩下的元素都拷贝进来
R[n2] = 10000000; //保证把剩下的元素都拷贝进来
for (i=0, j=0, k=p; k<=r; k++){
if (L[i]<=R[j]){
a[k] = L[i];i++;
}else{
a[k] = R[j];j++;
}
}
delete []L;
delete []R;
}
}
归并排序求逆序数
int rs;
void MergeSort(int *a, int p, int r){
if (p<r){
int q = (p+r)/2;
MergeSort(a, p, q);
MergeSort(a, q+1, r);
int n1 = q-p+1;
int n2 = r-q;
int *L = new int[n1+1];
int *R = new int[n2+1];
int i, j, k;
for (i=0; i<n1; i++)L[i] = a[p+i];
for (j=0; j<n2; j++)R[j] = a[q+j+1];
L[n1] = 10000000; //保证把剩下的元素都拷贝进来
R[n2] = 10000000; //保证把剩下的元素都拷贝进来
for (i=0, j=0, k=p; k<=r; k++){
if (L[i]<=R[j]){
a[k] = L[i];i++;
}else{
a[k] = R[j];j++;
rs+= q-p+1;
}
}
delete []L;
delete []R;
}
}
//测试方法
int main(){
int a[5] = {4,3,2,1,0};
rs = 0;
MergeSort1(a,0,4);
for(int i=0;i<5;i++)cout<<a[i]<<" ";cout<<endl;
cout<<rs<<endl;
}