-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountInverseBruteForce.java
More file actions
89 lines (72 loc) · 2.55 KB
/
CountInverseBruteForce.java
File metadata and controls
89 lines (72 loc) · 2.55 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* *****************************************************************************
* Name: Jaya Mukheerjee
* Count Inverse in an array:
* Last modified: Jan 1, 2022
**************************************************************************** */
import java.util.Arrays;
import java.util.Scanner;
public class CountInverseBruteForce {
public static int countBF(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] < nums[j]) {
count++;
}
}
}
return count;
}
public static int countMerge(int[] nums, int low, int mid, int high) {
int[] leftArr = Arrays.copyOfRange(nums, low, mid);
int[] rightArr = Arrays.copyOfRange(nums, mid + 1, high);
int i = 0, j = 0, k = low, swap = 0;
while (i < leftArr.length || j < rightArr.length) {
if (i < leftArr.length && j < rightArr.length) {
if (leftArr[i] > rightArr[j]) {
nums[k++] = rightArr[j++];
swap += (mid + 1) - (low + i);
}
else {
nums[k++] = leftArr[i++];
}
}
else if (i < leftArr.length) {
nums[k++] = leftArr[i++];
}
else {
nums[k++] = rightArr[j++];
}
}
return swap;
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = scn.nextInt();
}
//countBF(nums);
System.out.println(
mergeSortAndCount(nums, 0, nums.length - 1));
}
private static int mergeSortAndCount(int[] arr, int left,
int right) {
// Keeps track of the inversion count at a
// particular node of the recursion tree
int count = 0;
if (left < right) {
int m = (left + right) / 2;
// Total inversion count = left subarray count
// + right subarray count + merge count
// Left subarray count
count += mergeSortAndCount(arr, left, m);
// Right subarray count
count += mergeSortAndCount(arr, m + 1, right);
// Merge count
count += countMerge(arr, left, m, right);
}
return count;
}
}