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, stats) {
  const n = arr.length;
  if (n < 1) return;
  let max = arr[0];
  for (let i = 1; i < n; i++) max = Math.max(max, arr[i]);
  const maxDigits = max.toString().length;
  function msdSort(lo, hi, digit) {
    if (lo >= hi || digit < 0) return;
    const exp = Math.pow(10, digit);
    const buckets = Array.from({
      length: 10
    }, () => []);
    for (let i = lo; i <= hi; i++) {
      const d = Math.floor(arr[i] / exp) % 10;
      buckets[d].push(arr[i]);
    }
    let idx = lo;
    const starts = [];
    for (let b = 0; b < 10; b++) {
      starts.push(idx);
      for (let bucketIndex = 0; bucketIndex < buckets[b].length; bucketIndex++) {
        const v = buckets[b][bucketIndex];
        arr[idx] = v;
        write(idx, v);
        idx++;
      }
    }
    for (let b = 0; b < 10; b++) {
      if (buckets[b].length > 1) {
        msdSort(starts[b], starts[b] + buckets[b].length - 1, digit - 1);
      }
    }
    checkpoint(lo, n);
  }
  msdSort(0, n - 1, maxDigits - 1);
  for (let i = 0; i < n; i++) markSorted(i);
}