Mergesort Inversion Count Typed

Count inversions in a number array using a typed mergesort that counts crossings during the merge step.

TypescriptData Integrity

Code

typescriptsnippet
20 lines
function countInversions(arr: number[]): number {
  const tmp: number[] = new Array(arr.length);
  function merge(lo: number, mid: number, hi: number): number {
    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: number, hi: number): number {
    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);
}

Inside the snippet

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

The core work runs in nested loops — outer for (let x = lo; x <= hi; x++) tmp[x] = arr[x];, inner while (i < mid && j <= hi).

Watch out for

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

Putting it to use

The main signature reads const mid = (lo + hi + 1)

Core lines

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

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `mid`, `countInversions`, `merge` at load time.