首页 > 代码库 > 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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。