首页 > 代码库 > Counting Inversion Pairs in an Array

Counting Inversion Pairs in an Array

Given an array, for example, 2 4 6 1 3 5, an inversion pair is the pair whose first value is larger than its second value according to the sequence from left to right, (2,1) (4,1) (4,3) (6,1) (6,3) (6,5). The following code is an O(nlog(n)) algorithm based on merge sort to count the inversion pairs in an array.

long long inversionCount(vector<int> &A, int l, int r) {
	if (l >= r) return 0;
	int m = (l + r) >> 1;
	long long res = inversionCount(A, l, m);
	res += inversionCount(A, m+1, r);
	vector<int> B(A.begin()+l, A.begin()+r+1);
	int i = l, j = m + 1, k = l;
	while (i<=m && j<=r) {
		if (B[i-l] <= B[j-l]) {
			A[k++] = B[(i++)-l];
		} else {
			A[k++] = B[(j++)-l];
			res += m - i + 1;
		}
	}
	while (i <= m) A[k++] = B[(i++)-l];
	while (j <= r) A[k++] = B[(j++)-l];
	return res;
}