Repository navigation
Expand file tree
/
Copy pathCount Inversions
More file actions
80 lines (63 loc) · 1.94 KB
/
Copy pathCount Inversions
File metadata and controls
80 lines (63 loc) · 1.94 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
//{ Driver Code Starts
//Initial Template for Java
import java.util.*;
import java.io.*;
import java.lang.*;
class Sorting
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
long t = sc.nextLong();
while(t-- > 0)
{
long n = sc.nextLong();
long arr[] = new long[(int)n];
for(long i = 0; i < n; i++)
arr[(int)i] = sc.nextLong();
System.out.println(new Solution().inversionCount(arr, n));
}
}
}
// } Driver Code Ends
//User function Template for Java
class Solution {
static long inversionCount(long arr[], long N) {
long[] temp = new long[(int) N];
return mergeSortAndCountInversions(arr, temp, 0, (int) (N - 1));
}
static long mergeSortAndCountInversions(long arr[], long temp[], int left, int right) {
long count = 0;
if (left < right) {
int mid = (left + right) / 2;
count += mergeSortAndCountInversions(arr, temp, left, mid);
count += mergeSortAndCountInversions(arr, temp, mid + 1, right);
count += mergeAndCountSplitInversions(arr, temp, left, mid, right);
}
return count;
}
static long mergeAndCountSplitInversions(long arr[], long temp[], int left, int mid, int right) {
int i = left;
int j = mid + 1;
int k = left;
long count = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
count += (mid - i + 1);
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (i = left; i <= right; i++) {
arr[i] = temp[i];
}
return count;
}
}