Counting Inversion Pairs in an Array

时间:2014-05-13 08:03:58   收藏:0   阅读:338

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;
}


Counting Inversion Pairs in an Array,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!