-
Notifications
You must be signed in to change notification settings - Fork 0
/
countinversions.txt
47 lines (41 loc) · 1.05 KB
/
countinversions.txt
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
#include <bits/stdc++.h>
int merge(long long int arr[],long long int temp[],int left,int mid,int right)
{
int inv_count=0;
int i = left;
int j = mid;
int k = left;
while((i <= mid-1) && (j <= right)){
if(arr[i] <= arr[j]){
temp[k++] = arr[i++];
}
else
{
temp[k++] = arr[j++];
inv_count = inv_count + (mid - i);
}
}
while(i <= mid - 1)
temp[k++] = arr[i++];
while(j <= right)
temp[k++] = arr[j++];
for(i = left ; i <= right ; i++)
arr[i] = temp[i];
return inv_count;
}
int mergesort(long long *arr,long long *temp,int low,int high){
int mid=(low+high)/2;
int count=0;
if(high>low){
count+=mergesort(arr,temp,low,mid);
count+=mergesort(arr,temp,mid+1,high);
count+=merge(arr,temp,low,mid+1,high);
}
return count;
}
long long getInversions(long long *arr, int n){
// Write your code here.
long long int temp[n];
int ans=mergesort(arr,temp,0,n-1);
return ans;
}