-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount Inversions.java
More file actions
46 lines (43 loc) · 935 Bytes
/
Copy pathCount Inversions.java
File metadata and controls
46 lines (43 loc) · 935 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
public class Solution {
public static long merge(long[] arr,int start,int mid,int end,long[] temp){
int i=start;
int j=mid;
int k=start;
long len=0;
while(i<=mid-1 && j<=end){
if(arr[i]<=arr[j]){
temp[k++]=arr[i++];
}
else{
temp[k++]=arr[j++];
len += (mid-i);
}
}
while(i<=mid-1){
temp[k++]=arr[i++];
}
while(j<=end){
temp[k++]=arr[j++];
}
for(int l=start;l<=end;l++){
arr[l]=temp[l];
}
return len;
}
public static long divide(long[] arr,long[] temp,int start,int end){
long len=0;
if(start<end){
int middle = (start+end)/2;
len+=divide(arr,temp,start,middle);
len+=divide(arr,temp,middle+1,end);
len+=merge(arr,start,middle+1,end,temp);
}
return len;
}
public static long getInversions(long arr[], int n) {
// Write your code here.
long[] temp = new long[n];
long ans = divide(arr,temp,0,arr.length-1);
return ans;
}
}