-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count_Inversion.cpp
60 lines (57 loc) · 1.39 KB
/
Count_Inversion.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
59
60
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
long long count = 0;
void merge(long long A[], long long low, long long mid, long long high)
{
vector<long long> ans;
long long left = low;
long long right = mid + 1;
while (left <= mid && right <= high)
{
if (A[left] <= A[right])
{
ans.push_back(A[left]);
left++;
}
else
{
ans.push_back(A[right]);
count += (mid - left + 1);
right++;
}
}
while (left <= mid)
{
ans.push_back(A[left]);
left++;
}
while (right <= high)
{
ans.push_back(A[right]);
right++;
}
for (long long i = low; i <= high; i++)
{
A[i] = ans[i - low];
}
}
void mergeSort(long long A[], long long low, long long high)
{
long long mid;
if (low >= high)
return;
mid = (low + high) / 2;
mergeSort(A, low, mid);
mergeSort(A, mid + 1, high);
merge(A, low, mid, high);
}
long long int inversionCount(long long arr[], int n)
{
mergeSort(arr, 0, n - 1);
return count;
}
};