-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount inversion
64 lines (61 loc) · 1.45 KB
/
Count inversion
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
import java.util.* ;
import java.io.*;
public class Solution {
public static long getInversions(long arr[], int n) {
int low=0;
int high=n-1;
long k=mergesort(arr,low,high);
return k;
}
static long mergesort(long arr[],int low,int high)
{
long inv=0;
if(low<high)
{
int mid=(high+low)/2;
inv+=mergesort(arr,low,mid);
inv+=mergesort(arr,mid+1,high);
inv+=merge(arr,low,mid,high);
}return inv;
}
static long merge(long arr[],int low,int mid,int high)
{
long inv=0;
long left[]=new long[mid-low+1];
long right[]=new long[high-mid];
int i,j,k;
for(i=0;i<left.length;i++)
{
left[i]=arr[low+i];
}
for( j=0;j<right.length;j++)
{
right[j]=arr[mid+j+1];
}
i=0;j=0;k=low;
while(i<left.length && j<right.length)
{
if(left[i]<=right[j])
{
arr[k]=left[i];
i++;
k++;
}
else{
arr[k]=right[j];
j++;
k++;
inv+=left.length-i;
}
}
while(i<left.length)
{
arr[k++]=left[i++];
}
while(j<right.length)
{
arr[k++]=right[j++];
}
return inv;
}
}