problem: Given an array a,a has n distinct integers. Definition: If I<j and A[i]>a[j], the name (I,J) is an inverse pair (inversation) of a. An O (NLOGN) algorithm is designed to find the number of reverse pairs in a.
Obviously the worst case reversal pairs have n (n-1)/2, such as; 5 4 3 2 1 in reverse order, reverse pairs have (5-1) *5/2=10 pairs. If it is solved by brute force, the time complexity is O (N2), which is obviously not a good algorithm. Consider using a similar approach to merge sorting to solve this problem.
First, for an array of length n a[0...n-1], we can divide it into two lengths of N/2 sub-arrays L[0...N1]=A[0...N/2] and r[0...n2]=a[n/2+1...n-1], the total reverse order of =l in reverse order in +r to + Sweep the reverse order of L and R ;
For example, the array 2 3 8 6 1 is divided into two parts L:2 3 8 and R:6 1, so the left L in reverse order to 0, right R in reverse order (6,1) a total of 1 pairs, then sweep L with R (2,1), (3,1), (8,6), (8,1) altogether 4 pairs, so the total logarithm for 0+1+4=5 pair. Now the difficulty of the problem is how to seek the middle sweep that part of the reverse order, if the violence to beg, must O (N2). Let's take a look at the fact that if L were to be ordered, the R would be ordered, and the number of reverse orders that swept that part in the middle would not change, because L was separate from R. In this way, we can use the idea of merging sorting to design the algorithm, based on the reason that the design is correct in each sub-sequence of the collation of the sequence is in the reverse order of the series after the completion of the calculation. The C + + code is as follows:
#include <iostream>
using namespace Std;
#define Max_value 12343564
int count_reversations (int *a, int n);
int merge_reversations (int *a, int p, int r);
int main () {
int a[5] = {2,3,8,6,1};
cout << Count_reversations (A, 5) << Endl;
return 0;
}
int count_reversations (int*a, int n) {//interface function
Return merge_reversations (A, 0, n-1);
}
int merge_reversations (int *a, int p, int r) {
if (p>=r)
return 0;
int I, J, k,mid,n1,n2, reversations = 0;
Mid = (p + r) >> 1;
int next_count= merge_reversations (A, p, mid) + Merge_reversations (A, mid + 1, R);
N1 = mid-p + 1;
N2 = R-mid;
int *r = new INT[N2 + 1];
int *l = new INT[N1 + 1];
for (i = 0; i < N1; i++)
L[i] = a[i + P];
for (j = 0; J < N2; J + +)
R[J] = a[j + mid + 1];
L[N1] = r[n2] = Max_value; Set to maximum value, as Sentinel
i = j = 0;
for (k = p; k <= R; k++) {
if (L[i]>r[j]) {
Reversations +=n1-i;
A[K] = r[j++];
}
Else
A[K] = l[i++];
}
Delete[]r, L;
return reversations +next_count;
}
Calculating the number of inverse pairs of an array