Mergesort Inversion Count (JavaScript)
Count the number of inversions in an array using a modified mergesort that counts crossings during the merge step in O(n log n) time.
Code
function countInversions(arr) {
const tmp = new Array(arr.length);
function merge(lo, mid, hi) {
let i = lo, j = mid, k = lo, inv = 0;
for (let 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;
}
function sort(lo, hi) {
if (lo >= hi) return 0;
const mid = (lo + hi + 1) >>> 1;
return sort(lo, mid - 1) + sort(mid, hi) + merge(lo, mid, hi);
}
return sort(0, arr.length - 1);
}Report a problem with this exampleOpens a pre-filled issue on GitHub.