-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayInversions.cpp
More file actions
85 lines (71 loc) · 1.43 KB
/
ArrayInversions.cpp
File metadata and controls
85 lines (71 loc) · 1.43 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
#include <iostream>
#include <vector>
// QUESTION: https://www.techiedelight.com/inversion-count-array/
class InversionCount
{
private:
std::vector<int>& arr;
public:
InversionCount(std::vector<int>& a)
: arr(a)
{
}
int compute()
{
return computeHelper(0, arr.size() - 1);
}
private:
int computeHelper(int low, int high)
{
int inversion = 0;
if (low < high)
{
int mid = (high + low) / 2;
inversion += computeHelper(low, mid); // left inversions
inversion += computeHelper(mid + 1, high); // right inversions
inversion += splitInversions(low, mid, high); // split inversions
}
return inversion;
}
int splitInversions(int low, int mid, int high)
{
std::vector<int> temp(high - low + 1);
int count = 0;
int k = 0;
int i = low;
int j = mid + 1;
while (i <= mid && j <= high)
{
if (arr[j] < arr[i])
{
// Every subsequent element of i will be greater than j
// So, include all of them
count += (mid - i + 1);
temp[k++] = arr[j++];
} else {
temp[k++] = arr[i++];
}
}
while (i <= mid)
{
temp[k++] = arr[i++];
}
while (j <= high)
{
temp[k++] = arr[j++];
}
// Copy over temp to original array
for (i = low; i <= high; ++i)
{
arr[i] = temp[i - low];
}
return count;
}
};
int main()
{
std::vector<int> arr{ 1, 9, 6, 4, 5 };
InversionCount obj(arr);
std::cout << "Inversion count is " << obj.compute() << std::endl;
return 0;
}