-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInversionCount.java
More file actions
70 lines (57 loc) · 1.83 KB
/
InversionCount.java
File metadata and controls
70 lines (57 loc) · 1.83 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
import java.util.*;
import java.io.*;
public class InversionCount {
private static long invCnt = 0;
private static void merge(int[] a, int[] aux, int lo, int mid, int hi)
{
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++)
{
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (less(aux[j], aux[i])) {
a[k] = aux[j++];
invCnt += (mid+1-i);
}
else a[k] = aux[i++];
}
}
private static void sort(int[] a, int[] aux, int lo, int hi)
{
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid+1, hi);
merge(a, aux, lo, mid, hi);
}
public static void sort(int[] a)
{
int[] aux = new int[a.length];
sort(a, aux, 0, a.length - 1);
}
private static boolean less(int a, int b) {
int answer = a - b;
if (answer < 0) return true;
else return false;
}
public static void main(String[] args) throws FileNotFoundException {
int[] arr = new int[100000];
Scanner in = new Scanner(new BufferedReader(new FileReader("IntegerArray.txt")));
for (int i = 0; i < 100000; i++) {
arr[i] = in.nextInt();
}
//System.out.println(arr[0] + " " + arr[1] + " " + arr[2]);
//System.out.println(arr[99999]);
sort(arr);
/*
for (int i = 0; i < 10; i++) {
System.out.println(arr[i]);
}
*/
System.out.println(invCnt);
in.close();
}
}