Title: Gives an algorithm for determining the number of inverse pairs in any permutation of n different elements, with the worst case requiring Θ(NLGN) time. (Hint: Modify merge sort.) )
Idea: Modify the merge sort from large to small sort.
Merge sorting is divided into three steps: decomposition, resolution, and merging.
Decomposition: The permutation A is decomposed into A1,A2 two sub-permutations.
Settlement: The recursion from large to small arranges A1 and A2, in this same way recursively solves A1,A2 in reverse order to quantity.
Merge: Compare A1 elements [a1,a2,a3 ...] from large to small by recursively sorting the merge strategy. and the elements in A2 [b1,b2,b3 ...] .
1. if A1 is greater than B1, then A1 is greater than all elements in the A2, the number of reverse pairs plus length (A2), will A1 moving from A1 to output arrangement,A2 continues to compare with B1 .
2. if A1 is less than B1, then B1 is greater than all elements in the A1,B1 cannot be in reverse order with the elements in A1, B1 moving from A2 to output arrangement,B2 continues to compare with A1 .
3. until there are no elements in A1 or A2, move the remaining elements to the output arrangement.
The number of reversed pairs after merging is the sum of the number of reverse pairs in the pre- A1 and A2 plus the inverse logarithm added during the merge.
#include <iostream>using namespacestd;inta[ -];inttemp1[ -];inttemp2[ -];intMergeintLow1,intHIGH1,intLow2,intHIGH2) {//Merge Step intinver_num=0;//number of new reverse pairs added in the merge. inta_pos=Low1; intsize1=0;//first copy the two arrays to be merged into the temporary array Temp1 and TEMP2. while(low1<=high1) {Temp1[size1++]=a[low1++]; } intSize2=0; while(low2<=high2) {Temp2[size2++]=a[low2++]; } intI=0, j=0; while(size1!=0&&size2!=0){//Start Merging if(temp1[i]>Temp2[j]) {A[a_pos++]=temp1[i++]; Inver_num+=size2;//the number of reverse order increases. size1-=1; } Else{//temp1[i]<temp2[j],There are no identical elements. a[a_pos++]=temp2[j++]; Size2-=1; } } while(size2!=0){//copies the remaining elements to the output array. a[a_pos++]=temp2[j++]; Size2-=1; } while(size1!=0){//and the upper while only executes one. a[a_pos++]=temp1[i++]; Size1-=1; } returnInver_num;}intInversion (intLowintHigh ) { if(low>=High )return 0; intMid= (Low+high)/2; intleft_num=inversion (low,mid); intRight_num=inversion (mid+1, high); intMerge_num=merge (low,mid,mid+1, high); returnleft_num+right_num+Merge_num;}
[Introduction to algorithms] practice 2-4.D The number of reverse pairs in permutations