码迷,mamicode.com
首页 > 其他好文 > 详细

Counting Inversion Pairs in an Array

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

标签:merge   c++   algorithm   

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

标签:merge   c++   algorithm   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!