Mergesort Inversion Count (Java)

Count inversions in a Java array using a modified mergesort that counts crossings during the merge step.

JavaData Integrity

Code

javasnippet
20 lines
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;
    }
}

Inside the snippet

Mergesort Inversion Count (Java) keeps everything in the class InversionCount and the functions count, sort and merge.

Iteration happens inside for (int x = lo; x <= hi; x++) tmp[x] = arr[x]; — everything outside it runs once.

Putting it to use

The main signature reads public static long count(int[] arr)

Core lines

while (i < mid && j <= hi) { if (tmp[i] <= tmp[j]) arr[k++] = tmp[i++]; else { arr[k++] = tmp[j++]; inv += mid - i; } }
return sort(arr, lo, mid - 1) + sort(arr, mid, hi) + merge(arr, lo, mid, hi);
return sort(arr, 0, arr.length - 1);

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `count`, `sort`, `merge` at load time.