forked from sunnyshahabuddin/Coding-Ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountinversions
More file actions
53 lines (44 loc) · 993 Bytes
/
Countinversions
File metadata and controls
53 lines (44 loc) · 993 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
49
50
51
52
53
#include<bits/stdc++.h>
using namespace std;
int getSum(int BITree[], int index)
{
int sum = 0; // Initialize result
while (index > 0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
void updateBIT(int BITree[], int n, int index, int val)
{
while (index <= n)
{
BITree[index] += val;
index += index & (-index);
}
}
int getInvCount(int arr[], int n)
{
int invcount = 0;
int maxElement = 0;
for (int i=0; i<n; i++)
if (maxElement < arr[i])
maxElement = arr[i];
int BIT[maxElement+1];
for (int i=1; i<=maxElement; i++)
BIT[i] = 0;
for (int i=n-1; i>=0; i--)
{
invcount += getSum(BIT, arr[i]-1);
updateBIT(BIT, maxElement, arr[i], 1);
}
return invcount;
}
int main()
{
int arr[] = {8, 4, 2, 1};
int n = sizeof(arr)/sizeof(int);
cout << "Number of inversions are : " << getInvCount(arr,n);
return 0;
}