-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcountInversions.java
More file actions
53 lines (47 loc) · 1.38 KB
/
countInversions.java
File metadata and controls
53 lines (47 loc) · 1.38 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
50
51
52
53
class Solution {
static int inversionCount(int arr[]) {
return mergeSortAndCount(arr, 0, arr.length - 1);
}
static int mergeSortAndCount(int arr[], int left, int right) {
int count = 0;
if (left < right) {
int mid = (left + right) / 2;
count += mergeSortAndCount(arr, left, mid);
count += mergeSortAndCount(arr, mid + 1, right);
count += mergeAndCount(arr, left, mid, right);
}
return count;
}
static int mergeAndCount(int arr[], int left, int mid, int right) {
int count = 0;
int n1 = mid - left + 1;
int n2 = right - mid;
int[] leftArr = new int[n1];
int[] rightArr = new int[n2];
System.arraycopy(arr, left, leftArr, 0, n1);
System.arraycopy(arr, mid + 1, rightArr, 0, n2);
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
i++;
} else {
arr[k] = rightArr[j];
count += (n1 - i);
j++;
}
k++;
}
while (i < n1) {
arr[k] = leftArr[i];
i++;
k++;
}
while (j < n2) {
arr[k] = rightArr[j];
j++;
k++;
}
return count;
}
}