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;
}
}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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.