Radix Sort (LSD)

Sorts by processing digits from least significant to most significant, using counting sort as a subroutine.

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

Sorts by processing digits from least significant to most significant, using counting sort as a subroutine.

Implementation

function radixSort(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 sorted = new Set();
  for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) {
    const output = new Array(n);
    const count = new Array(10).fill(0);
    for (let i = 0; i < n; i++) {
      count[Math.floor(arr[i] / exp) % 10]++;
    }
    for (let i = 1; i < 10; i++) count[i] += count[i - 1];
    for (let i = n - 1; i >= 0; i--) {
      const digit = Math.floor(arr[i] / exp) % 10;
      output[count[digit] - 1] = arr[i];
      count[digit]--;
    }
    for (let i = 0; i < n; i++) {
      arr[i] = output[i];
      write(i, output[i]);
    }
    checkpoint(exp, max);
  }
  for (let i = 0; i < n; i++) markSorted(i);
}