-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcountinversions.cpp
53 lines (44 loc) · 1022 Bytes
/
countinversions.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
#include <bits/stdc++.h>
void merge(long long*& arr,int low,int mid,int high,long long& count ){
vector<int> temp;
int i=low;
int j=mid+1;
while(i<=mid && j<=high){
if(arr[i]<arr[j]){
temp.push_back(arr[i]);
i++;
}else{
count+=mid-i+1;
temp.push_back(arr[j]);
j++;
}
}
while(i<=mid){
temp.push_back(arr[i]);
i++;
}
while(j<=high){
temp.push_back(arr[j]);
j++;
}
for(int i=low;i<=high;i++){
arr[i]=temp[i-low];
}
}
void mergesort(long long*& arr,int low,int high,long long& count){
if(low>=high){
return ;
}
int mid=(low+high)/2;
mergesort(arr,low,mid,count);
mergesort(arr,mid+1,high,count);
merge(arr,low,mid,high,count);
}
long long getInversions(long long *arr, int n){
// Write your code here.
long long count=0;
int low=0;
int high=n-1;
mergesort(arr,low,high,count);
return count;
}