Title: Two digits in an array if the previous number is greater than the following number, then these two numbers form a reverse-order pair.
Enter an array to find out the total number of reverse pairs in this array.
Using the merge Sort method, the auxiliary space is an ordered array, which in turn compares the preceding large numbers to calculate the whole reverse logarithm, not to be compared individually.
Complexity of Time: O (NLOGN)
Code:
* * * main.cpp * * Created on:2014.6.12 * author:spike//*eclipse CDT, gcc 4.8.1*/#incl Ude <stdio.h> #include <stdlib.h> #include <string.h> int inversepairscore (int* data, int*
Copy, int start, int end) {if (start = = end) {Copy[start] = Data[start];
return 0;
int length = (end-start)/2;
int left = Inversepairscore (copy, data, start, start+length);
int right = Inversepairscore (copy, data, start+length+1, end); int i = start+length;
the subscript int J = End of the last digit of the first half paragraph;
int indexcopy = end;
int count = 0; while (I>=start && j>=start+length+1) {if (Data[i] > Data[j]) {copy[indexcopy--
] = data[i--];
Count + = J-start-length;
else {copy[indexcopy--] = data[j--];
} for (; i>=start;-i) copy[indexcopy--] = Data[i]; for (;j>=start+length+1;
--J) copy[indexcopy--] = Data[j];
return left+right+count;
int Inversepairs (int* data, int length) {if (data = NULL | | | length < 0) return 0;
int *copy = new Int[length];
for (int i=0; i<length; ++i) copy[i] = Data[i];
int count = Inversepairscore (data, copy, 0, length-1);
delete[] copy;
return count;
int main (void) {int data[] = {7, 5, 6, 4};
int result = Inversepairs (data, 4);
printf ("result =%d\n", result);
return 0; }
Output:
result = 5
This column more highlights: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
Author: csdn Blog Caroline-wendy