-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path012_Count Inversions.cpp
58 lines (46 loc) · 1.14 KB
/
012_Count Inversions.cpp
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
#include <bits/stdc++.h>
long long merge(int lb, int mid, int ub,long long *arr, vector<long long>& temp)
{
int i = lb, j = mid, k = lb;
long long inversions = 0;
while(i <= mid-1 and j <= ub)
{
if(arr[i] <= arr[j])
{
temp[k++] = arr[i++];
}
else
{
temp[k++] = arr[j++];
inversions += (mid - i);
}
}
while(i <= mid-1)
{
temp[k++] = arr[i++];
}
while(j <= ub)
{
temp[k++] = arr[j++];
}
for(int i = lb ; i <= ub; ++i)
arr[i] = temp[i];
return inversions;
}
long long mergeSort(int start, int end , long long *arr, vector<long long>& temp)
{
int inversions = 0;
if(start < end)
{
long long mid = start + (end - start)/2;
inversions += mergeSort(start, mid, arr, temp);
inversions += mergeSort(mid+1, end, arr, temp);
inversions += merge(start, mid+1, end, arr, temp);
}
return inversions;
}
long long getInversions(long long *arr, int n){
// Write your code here.
vector<long long> temp(n);
return mergeSort(0, n-1, arr, temp);
}