Radix Sort (MSD)

Like LSD Radix Sort but processes from the most significant digit first. Can short-circuit on already-sorted data.

Best O(d(n+k)) Avg O(d(n+k)) Worst O(d(n+k)) Space O(n+k) Stable Yes In-place No Distribution

How it works

Like LSD Radix Sort but processes from the most significant digit first. Can short-circuit on already-sorted data.

Implementation

function radixMSDSort(arr, lo = 0, hi = arr.length-1, d) {
  if (d === undefined) d = Math.max(...arr).toString().length - 1;
  if (lo >= hi || d < 0) return;
  const exp = Math.pow(10, d);
  const bk = Array.from({length: 10}, () => []);
  for (let i = lo; i <= hi; i++)
    bk[Math.floor(arr[i] / exp) % 10].push(arr[i]);
  let idx = lo;
  for (let b = 0; b < 10; b++) {
    const start = idx;
    for (const v of bk[b]) arr[idx++] = v;
    if (bk[b].length > 1)
      radixMSDSort(arr, start, idx-1, d-1);
  }
}