If the first two digits in the array are greater than the subsequent digits, the two digits form a reverse order pair, enter an array, and find the total number of the reverse order pairs of the array.
Train of Thought: Use the merged sorting of Deformation
# Include <iostream> using namespace STD; int inversepairs (int * data, int * Buf, int L, int R) {If (L> = r) return 0; // initialize the required variable. P1 points to the rightmost of the left sub-array, P2 points to the rightmost int count of the right sub-array = 0; int mid = (L + r)/2; int p1 = mid; int P2 = r; int lpairs = inversepairs (data, Buf, L, mid); int rpairs = inversepairs (data, Buf, Mid + 1, R ); int length = r-L + 1; // copy data to the secondary array for (INT curr = L; curr <= r; curr ++) {Buf [curr] = data [curr];} // merge and sort. Pay attention to the order in which the branches appear and avoid the array operation going out of bounds for (INT curr = R; curr> = L; curr --) {If (P1 <L) {data [curr] = Buf [P2 --];} else {If (P2 <Mid + 1) {data [curr] = Buf [P1 --];} else {If (BUF [P1]> Buf [P2]) {data [curr] = Buf [P1 --]; count + = (P2-mid);} else {data [curr] = Buf [P2 --] ;}}} return (lpairs + rpairs + count );} int main () {# If 0 int data [4] = {7, 5, 6, 4}; int temp [4] = {0}; int mycount = inversepairs (data, temp, 0, 3); For (INT I = 0; I <4; I ++) cout <data [I] <'\ T'; cout <Endl; cout <mycount; # endif const int num = 6; int data [num] = {6, 2, 3, 6, 5, 0 }; int temp [num] = {0}; int mycount = inversepairs (data, temp, 0, 5); For (INT I = 0; I <num; I ++) cout <data [I] <'\ T'; cout <Endl; cout <mycount; System ("pause ");}
Reverse Order pairs in the array