Mergesort Inversion Count (Java)
Count inversions in a Java array using a modified mergesort that counts crossings during the merge step.
Code
public class InversionCount {
static int[] tmp;
public static long count(int[] arr) {
tmp = new int[arr.length];
return sort(arr, 0, arr.length - 1);
}
static long sort(int[] arr, int lo, int hi) {
if (lo >= hi) return 0;
int mid = (lo + hi + 1) >>> 1;
return sort(arr, lo, mid - 1) + sort(arr, mid, hi) + merge(arr, lo, mid, hi);
}
static long merge(int[] arr, int lo, int mid, int hi) {
int i = lo, j = mid, k = lo; long inv = 0;
for (int x = lo; x <= hi; x++) tmp[x] = arr[x];
while (i < mid && j <= hi) { if (tmp[i] <= tmp[j]) arr[k++] = tmp[i++]; else { arr[k++] = tmp[j++]; inv += mid - i; } }
while (i < mid) arr[k++] = tmp[i++];
while (j <= hi) arr[k++] = tmp[j++];
return inv;
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.