Skip to content

Commit f31b10f

Browse files
Merge pull request #575 from yassin64b/cpp_count_inversions
Add function counting the number of inversions based on merge sort
2 parents 530ec7a + c077b93 commit f31b10f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
long long count_inversions(int *a, int n) {
7+
if (n <= 1) {
8+
return 0;
9+
}
10+
int sz1 = n / 2, sz2 = n - sz1;
11+
12+
// get count of inversions in left and right half
13+
long long res = count_inversions(a, sz1) + count_inversions(a + sz1, sz2);
14+
15+
// merge both halves (now copied into t1, resp. t2) into a
16+
vector<int> t1(a, a + sz1), t2(a + sz1, a + n);
17+
int k = 0, i = 0, j = 0;
18+
while (i < sz1 && j < sz2) {
19+
if (t1[i] <= t2[j]) {
20+
a[k++] = t1[i++];
21+
22+
// all elements in t2[0..j-1] (which are j elements) are smaller than t1[i]
23+
// and are to the right of t1[i] in the original array --> form an inversion
24+
res += j;
25+
} else {
26+
a[k++] = t2[j++];
27+
}
28+
}
29+
while (i < sz1) {
30+
a[k++] = t1[i++];
31+
res += j; // j == sz2 holds here
32+
}
33+
while (j < sz2) {
34+
a[k++] = t2[j++];
35+
}
36+
return res;
37+
}
38+
39+
int main() {
40+
vector<int> v{10, 10, 20, 30, 12, 8, 9, 14, 13, 11};
41+
cout << "Given array has " << count_inversions(&v[0], v.size()) << " inversions.\n";
42+
return 0;
43+
}

0 commit comments

Comments
 (0)