-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathinversionCount.cpp
More file actions
48 lines (40 loc) · 953 Bytes
/
inversionCount.cpp
File metadata and controls
48 lines (40 loc) · 953 Bytes
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
#include<iostream>
using namespace std;
//to count the number of inversion pairs in an array
int merge(int *a, int start, int end) {
int temp[100];
int mid = (start+end)/2;
int i=start, j=mid+1, k=start;
int count = 0; //no of cross inversions
while(i<=mid && j<=end) {
if(a[i]<=a[j])
temp[k++] = a[i++];
else {
temp[k++] = a[j++];
count += mid - i + 1;
}
}
while(i<=mid)
temp[k++] = a[i++];
while(j<=end)
temp[k++] = a[j++];
for(int i=start;i<=end;i++) {
a[i] = temp[i];
}
return count;
}
int inversionCount(int a[], int start, int end) {
if(start>=end)
return 0;
int mid = (start+end)/2;
int x = inversionCount(a, start, mid);
int y = inversionCount(a, mid+1, end);
int z = merge(a, start, end);
return x + y + z;
}
int main() {
int arr[] = {1, 5, 2, 6, 3, 0};
//inversions go like -> (1, 0), (5, 3), (5, 2), (5, 0), (2, 0), (6, 0), (3, 0), (6, 3)
cout<<inversionCount(arr, 0, 5);
return 0;
}