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.

JavascriptData Integrity

Code

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

What the code does

Count the functions mid, countInversions, merge and sort as the entire surface area of Mergesort Inversion Count (JavaScript).

The structure is a loop within a loop: for (let x = lo; x <= hi; x++) tmp[x] = arr[x]; outside, while (i < mid && j <= hi) inside.

What to watch for

  • The guard lo >= hi short-circuits the flow with an early return when its condition holds.

Applying it

The primary signature is const mid = (lo + hi + 1)

Statements that matter

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

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `mid`, `countInversions`, `merge` at load time.