-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInversionCount.cpp
More file actions
64 lines (54 loc) · 1.48 KB
/
InversionCount.cpp
File metadata and controls
64 lines (54 loc) · 1.48 KB
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
55
56
57
58
59
60
61
62
63
64
long long merge(long long arr[], int left, int mid, int right){
int i = left, j = mid, k = 0;
long long invCount = 0;
int temp[(right - left + 1)];
while ((i < mid) && (j <= right)){
if (arr[i] <= arr[j]){
temp[k] = arr[i];
++k;
++i;
}
else{
temp[k] = arr[j];
invCount += (mid - i);
++k;
++j;
}
}
while (i < mid){
temp[k] = arr[i];
++k;
++i;
}
while (j <= right){
temp[k] = arr[j];
++k;
++j;
}
for (i = left, k = 0; i <= right; i++, k++){
arr[i] = temp[k];
}
return invCount;
}
// Function to split two subarrays and then merge them and count inversions.
long long mergeSort(long long arr[], int left, int right){
long long invCount = 0;
if (right > left){
int mid = (right + left) / 2;
/*
Divide the array into two parts
total inversion count will be the
sum of 'INVCOUNT' of left part +
'INVCOUNT' of right part + 'INVCOUNT' of
their combined part.
*/
invCount = mergeSort(arr, left, mid);
invCount += mergeSort(arr, mid + 1, right);
// Merge both parts and count their combined inversions.
invCount += merge(arr, left, mid + 1, right);
}
return invCount;
}
long long getInversions(long long arr[], int n){
return mergeSort(arr, 0, n - 1);
}