/* copyright "sword refers to the offer--name of the enterprise interviewing the typical programming questions" all the source of the topic: Fifth chapter Optimization time and Space efficiency P189////////////////////////////////// Enter an array to find out the total number of reverse pairs in this array for example, in the array {7,5,6,4}, there are altogether 5 pairs of reverse pairs, respectively {7,6},{7,5},{7,4},{6,4},{5,4}/////////////////////////////// , Space complexity O (1) Another method is to merge the sorting method, Time complexity O (NLOGN), Space complexity O (n) decomposition of an array, until the unit length, if the following number is less than the previous number, it is clearly reverse, and then merge two units of length of the array * * #include <
stdio.h> #include <malloc.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;
Computes the left and right sides of the array int left=inversepairscore (data, copy, start, start+length);
int Right=inversepairscore (data, copy, start+length+1, end);
The position of the last digit of the first segment array int i=start+length;
The position of the last digit of the second segment array int j=end;
int count = 0;
int copy_index = end;
while (I>=start && j> (start+length)) {if (Data[i]>data[j]) {copy[copy_index--] = data[i--];
Count + = J-start-length; else {copy[copy_index--] = data[j--];
()//fill in the remainder for (; i>=start;-i) copy[copy_index--] = Data[i];
for (; j>start+length;--j) copy[copy_index--] = Data[j];
The original book does not have this code, may be the book when the Missing for (I=start i<=end; ++i) data[i] = Copy[i];
Return left + right + count;
int inversepairs (int *data, int length) {if (Data==null | | length<0) {return 0;
int *copy = (int*) malloc (sizeof (int) *length);
int i;
for (I=0;i<length;++i) copy[i]=data[i];
int count = Inversepairscore (data, copy, 0, length-1);
Free (copy);
return count;
int main () {//int arr[4]={7,5,6,4};
int arr[1]={1};
int *arr = NULL;
int arr[3] = {3,1,2};
printf ("Count =%d \ n", Inversepairs (arr,3));
return 0; }