归并排序求逆序对
将里面reverseCount删除就可以作为归并排序代码。归并排序是稳定的。
#include <iostream> using namespace std; #define MAX_VALUE 0X7FFFFFFF int Merge(int arr[],int start,int mid,int high) { int i = start; int j = mid + 1; int k = start; int reverseCount = 0; int *temp = new int[high+1]; while(i<=mid&&j<=high){ if(arr[i]<=arr[j]){ temp[k++] = arr[i++]; }else{ temp[k++] = arr[j]; reverseCount += mid - i + 1; // for(int w=i;w<=mid;w++){ // cout<<"("<<arr[w]<<","<<arr[j]<<")"<<endl; // } j++; } } while(i<=mid)temp[k++] = arr[i++]; while(j<=high)temp[k++] = arr[j++]; for(int i=start;i<=high;++i){ arr[i] = temp[i]; } delete[] temp; return reverseCount; } int Merge1(int arr[],int low,int mid,int high) { int num1 = mid - low + 1; int num2 = high - mid; int *temp1 = new int[num1+1]; int *temp2 = new int[num2+1]; int reverseCount = 0; for(int i=0;i<num1;++i)temp1[i] = arr[i+low]; temp1[num1] = MAX_VALUE;//哨兵节点 for(int i=0;i<num2;++i)temp2[i] = arr[i+mid + 1]; temp2[num2] = MAX_VALUE;//哨兵节点 int index1 = 0; int index2 = 0; for(int k=low;k<=high;k++){//直到high,滤除哨兵节点 if(temp1[index1] <= temp2[index2]){ arr[k] = temp1[index1++]; }else{ arr[k] = temp2[index2++]; reverseCount += num1 - index1; } } delete[] temp1; delete[] temp2; return reverseCount; } int MergeSort(int arr[],int start,int end) { int reverseCount = 0; if(start<end){ int mid = start + (end - start>>1); //左子数组逆序对 reverseCount += MergeSort(arr,start,mid); //右子数组逆序对 reverseCount += MergeSort(arr,mid+1,end); //数组与数组之间的逆序对 reverseCount += Merge(arr,start,mid,end); } return reverseCount; } int main() { int arr[]={1,3,1,8,2,4,6,5}; for(int i=0;i<8;i++){ cout<<arr[i]<<" "; } cout<<endl; cout<<"The reverse count:"<<MergeSort(arr,0,7)<<endl; for(int i=0;i<8;i++){ cout<<arr[i]<<" "; } cout<<endl; system("pause"); return 0; }