Reverse-order code in the array (C)
This address: Http://blog.csdn.net/caroline_wendy
Title: The two numbers in the array assume that the previous number is greater than the following number, then these two numbers form an inverse pair.
Enter an array to find the total number of reverse pairs in this array.
Using the merge sort method, the auxiliary space is a sort of array, in order to compare the larger number in the front, to calculate the overall inverse logarithm, not one by one comparison.
Complexity of Time: O (NLOGN)
Code:
/* * main.cpp * * Created on:2014.6.12 * author:spike *//*eclipse CDT, gcc 4.8.1*/#include <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 last digit of the first half is subscript int j = End;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 L Eft+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);d elete[] 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
Programming algorithms-Reverse-order code in arrays (C)