-
Notifications
You must be signed in to change notification settings - Fork 0
/
InversionCount.cpp
68 lines (51 loc) · 1.25 KB
/
InversionCount.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
61
62
63
64
65
66
67
68
@chiranjeevi
Date: 19-May-17
#include <iostream>
#include <algorithm>
using namespace std;
void print(int arr[], int n){
for(int i=0; i<n; i++)
cout<<arr[i]<<" ";
cout<<endl;
}
int countInversions(int arr[], int aux[], int lo, int mid, int hi, int count){
for(int i=lo; i<=hi; i++)
aux[i]=arr[i];
for(int k=lo,i=lo,j=mid+1; k<=hi; k++){
if(i>mid){
arr[k]=aux[j++];
}
else if(j>hi){
arr[k]=aux[i++];
}
else if(aux[i]<aux[j]){
arr[k]=aux[i++];
count+=hi-j+1;
}
else{
arr[k]=aux[j++];
}
}
return count;
}
int findInversions(int arr[], int aux[], int lo, int hi, int count){
if(hi<=lo)
return count;
int mid=lo+(hi-lo)/2;
count=findInversions(arr,aux,lo,mid,count) + findInversions(arr,aux,mid+1,hi,count);
return countInversions(arr,aux,lo,mid,hi,count);
}
int main() {
int n,no_of_invers;
cin>>n;
int arr[n],aux[n];
for(int i=0; i<n; i++){
arr[i]=20-i;
}
random_shuffle(arr,arr+n);
print(arr,n);
no_of_invers=findInversions(arr,aux,0,n-1,0);
print(arr,n);
cout<<"No of inversions "<<(n*(n-1))/2-no_of_invers;
return 0;
}