-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16.Count_Inversions.cpp
More file actions
85 lines (69 loc) · 1.49 KB
/
16.Count_Inversions.cpp
File metadata and controls
85 lines (69 loc) · 1.49 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//Using Enhaced Merge Sort
//two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j
#include<iostream>
using namespace std;
int countAndMerge(int arr[], int low, int mid, int high)
{
int n1 = mid - low + 1;
int n2 = high - mid;
int left[n1], right[n2];
for(int i = 0; i < n1; i++)
{
left[i] = arr[low + i];
}
for (int i = 0; i < n2; i++)
{
right[i] = arr[mid + 1 + i];
}
int i = 0, j = 0, k = low;
int res = 0;
while(i < n1 && j < n2)
{
if(left[i] <= right[j])
{
arr[k] = left[i];
k++;
i++;
}
else
{
arr[k] = right[j];
k++;
j++;
res = res + (n1-i);
}
}
while(i < n1)
{
arr[k] = left[i];
k++;
i++;
}
while(j < n2)
{
arr[k] = right[j];
k++;
j++;
}
return res;
}
int countInv(int arr[], int low, int high)
{
int res = 0;
if(high > low)
{
int mid = low + (high-low)/2;
res += countInv(arr, low, mid);
res += countInv(arr, mid+1, high);
res += countAndMerge(arr, low, mid, high);
}
return res;
}
int main()
{
int arr[] = { 1, 20, 6, 4, 5 };
int n = sizeof(arr)/sizeof(int);
int ans = countInv(arr, 0, n-1);
cout << "Number of inversions are : " << ans;
return 0;
}