forked from iRupam/NewtonSchoolInfinityJune21
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInversionCount.java
More file actions
49 lines (40 loc) · 1.35 KB
/
InversionCount.java
File metadata and controls
49 lines (40 loc) · 1.35 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
package InfinityJune21.DivideAndConquer;
import java.util.Arrays;
public class InversionCount {
static int mergeAndCount(int arr[], int l, int m, int r) {
int left[] = Arrays.copyOfRange(arr, l, m + 1);
int right[] = Arrays.copyOfRange(arr, m + 1, r + 1);
int i = 0, j = 0, k = l, swaps = 0;
while(i < left.length && j < right.length) {
if(left[i] <= right[j]) {
arr[k++] = left[i++];
}
else {
arr[k++] = right[j++];
swaps = swaps + (m + 1) - (l + i);
}
}
while(i < left.length) {
arr[k++] = left[i++];
}
while(j < right.length) {
arr[k++] = right[j++];
}
return swaps;
}
static int mergeSortAndCount(int arr[], int l, int r) {
int count = 0;
if(l < r) {
int m = (l + r) / 2;
count += mergeSortAndCount(arr, l, m);
count += mergeSortAndCount(arr, m + 1, r);
count += mergeAndCount(arr, l, m, r);
}
return count;
}
public static void main(String[] args) {
int arr[] = {1, 20, 6, 4, 5};
int numberOfInversions = mergeSortAndCount(arr, 0, arr.length - 1);
System.out.println(numberOfInversions);
}
}