-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount Inversions
More file actions
52 lines (46 loc) · 1.13 KB
/
Count Inversions
File metadata and controls
52 lines (46 loc) · 1.13 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
https://www.codingninjas.com/studio/problems/count-inversions_615?leftPanelTab=0
#include <bits/stdc++.h>
long long merge(long long *arr,int low,int mid,int high){
int left=low;
int right=mid+1;
long long cnt=0;
vector<int> temp;
while((left<=mid) && (right<=high)){
if(arr[left]<arr[right]){
temp.push_back(arr[left]);
left++;
}
else{
temp.push_back(arr[right]);
cnt+=(mid-left+1);
right++;
}
}
while(left<=mid){
temp.push_back(arr[left]);
left++;
}
while(right<=high){
temp.push_back(arr[right]);
right++;
}
for(int i=left;i<=right;i++){
arr[i]=temp[i-low];
}
return cnt;
}
long long mergeSort(long long *arr,int left,int right){
int mid=0;
long long cnt=0;
if(left<right){
mid=(left+right)/2;
cnt+=mergeSort(arr,left,mid);
cnt+=mergeSort(arr,mid+1,right);
cnt+=merge(arr,left,mid,right);
}
return cnt;
}
long long getInversions(long long *arr, int n){
long long total=mergeSort(arr,0,n-1);
return total;
}