-
Notifications
You must be signed in to change notification settings - Fork 0
/
Inversion Count -Merge Sort(Efiicient)
55 lines (44 loc) · 1.27 KB
/
Inversion Count -Merge Sort(Efiicient)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
long long int countAndMerge(long long arr[], long long l, long long m, long long r) {
long long int n1 = m - l + 1;
long long int n2 = r - m;
vector<long long int> left(n1);
vector<long long int> right(n2);
for (int i = 0; i < n1; i++) {
left[i] = arr[l + i];
}
for (int i = 0; i < n2; i++) {
right[i] = arr[m + 1 + i];
}
long long int i = 0, j = 0, k = l;
long long int res = 0;
while (i < n1 && j < n2) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
res += (n1 - i); // Counting the inversions
}
}
while (i < n1) {
arr[k++] = left[i++];
}
while (j < n2) {
arr[k++] = right[j++];
}
return res;
}
long long int merge(long long arr[], long long l, long long r) {
long long int p = 0;
if (l < r) {
long long int m = l + (r - l) / 2;
// Recursively count inversions in left and right subarrays
p += merge(arr, l, m);
p += merge(arr, m + 1, r);
// Count inversions during the merge process
p += countAndMerge(arr, l, m, r);
}
return p;
}
long long int inversionCount(long long arr[], int n) {
return merge(arr, 0, n - 1);
}