This post shows how to implement Radix Sort in JavaScript — another non-comparison-based sorting algorithm that sorts numbers digit by digit, and a less common but interesting algorithm to know for interviews involving large sets of integers.

Radix sort in JavaScript:

Explanation:
Radix sort sorts numbers one digit position at a time, starting from the least significant digit (the ones place) and working toward the most significant digit, using a stable sort (like counting sort) at each step. Because it never directly compares two full numbers to each other, it can sort integers faster than comparison-based sorts when the numbers don't have too many digits.


See Radix Sort in Action

Drag the slider to watch elements distribute into digit buckets and collect back, pass by pass, or use Play to run it automatically.


JavaScript Program to Implement Radix Sort

function radixSort(arr) {
  const max = Math.max(...arr);

  for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) {
    arr = countingSortByDigit(arr, exp);
  }

  return arr;
}

function countingSortByDigit(arr, exp) {
  const output = new Array(arr.length).fill(0);
  const count = new Array(10).fill(0);

  for (const num of arr) {
    const digit = Math.floor(num / exp) % 10;
    count[digit]++;
  }

  for (let i = 1; i < 10; i++) {
    count[i] += count[i - 1];
  }

  for (let i = arr.length - 1; i >= 0; i--) {
    const digit = Math.floor(arr[i] / exp) % 10;
    output[count[digit] - 1] = arr[i];
    count[digit]--;
  }

  return output;
}

const numbers = [170, 45, 75, 90, 802, 24, 2, 66];
console.log("Sorted array:", radixSort(numbers));

Output:

Sorted array: [ 2, 24, 45, 66, 75, 90, 170, 802 ]

Radix sort is a good example of how non-comparison sorts can beat the usual O(n log n) limit for the right kind of data. For a more commonly asked alternative, see Counting Sort, which radix sort builds on. Try it with your own numbers in our Code Runner.


Frequently Asked Questions About Radix Sort in JavaScript

What is the time complexity of radix sort?

Radix sort runs in O(d * (n + k)) time, where d is the number of digits in the largest number, n is the number of elements, and k is the range of each digit (10, for base-10 digits).

How is radix sort different from counting sort?

Counting sort sorts based on the full value of each element in one pass. Radix sort applies a stable counting sort repeatedly, once per digit position, which lets it handle a much larger range of values efficiently than counting sort alone could.

When would I actually use radix sort?

It's most useful for sorting large collections of integers (or fixed-length strings) where the number of digits is small relative to the number of elements — common in specialized applications rather than everyday general-purpose sorting.