首页 > 其他 > 详细

Counting Inversion Pairs in an Array

时间:2014-05-13 08:03:25      阅读:500      评论:0      收藏:0      [点我收藏+]

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

Counting Inversion Pairs in an Array

原文:http://blog.csdn.net/jsc0218/article/details/25568697

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!