-
Notifications
You must be signed in to change notification settings - Fork 0
/
DevideAndConquer_InversionCount.java
50 lines (40 loc) · 1.22 KB
/
DevideAndConquer_InversionCount.java
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
public class DevideAndConquer_InversionCount {
public static int merge_count(int[] arr, int si, int ei){
int inv = 0;
if (si>=ei) return 0;
int mid = si + (ei-si)/2;
inv += merge_count(arr, si, mid);
inv += merge_count(arr, mid+1, ei);
inv += merge(arr, si, mid, ei);
return inv;
}
public static int merge(int[] arr, int si, int mid, int ei){
int inv = 0;
int i = si;
int j = mid+1;
int k = 0;
int[] temp = new int[ei-si+1];
while (i<=mid && j<=ei){
if (arr[i]<arr[j]){
temp[k] = arr[i];
i++;
}else {
temp[k] = arr[j];
j++;
inv = inv + (mid+1-i);
}
k++;
}
while (i<=mid) temp[k++] = arr[i++];
while (j<=ei) temp[k++] = arr[j++];
for (k=0, i=si; k< temp.length; k++, i++){
arr[i] = temp[k];
}
return inv;
}
public static void main(String[] args){
int[] arr = {2, 4, 1, 3, 5};
int ans = merge_count(arr, 0, arr.length-1);
System.out.println(ans);
}
}