Typorithm · hard

Radix Sort

▷ Interactive algorithm labradix-sortsortingdistributiondigitsnon-comparison
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Radix Sort

0%

Sorting Algorithms

Radix Sort sorts non-negative integers one digit place at a time using stable buckets.

Radix Sort avoids direct value comparisons and groups numbers by digits.

It starts at the ones place, then moves to tens, hundreds, and so on.

Each pass places values into buckets 0 through 9 and flattens those buckets back into the array.

The per-digit passes must be stable so earlier digit order is preserved while later digits are processed.

For bounded digit counts, the runtime is O(d * (n + b)), where d is digit count and b is bucket count.

Preparing algorithm lab…
01

Works on non-negative integer keys.

02

Process least significant digit first.

03

Use ten buckets for decimal digits.

04

Stable bucket order is essential.

05

Runtime depends on digit count, not comparisons.

function radixSort(arr) {
  if (arr.length <= 1) return arr;

  let max = Math.max(...arr);
  let place = 1;

  while (Math.floor(max / place) > 0) {
    const buckets = Array.from({ length: 10 }, () => []);

    for (const value of arr) {
      const digit = Math.floor(value / place) % 10;
      buckets[digit].push(value);
    }

    arr = buckets.flat();
    place *= 10;
  }

  return arr;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Small input

Empty and one-item arrays are already sorted.

if (arr.length <= 1) return arr

2. Largest value

The largest value tells us how many digit places to process.

let max = Math.max(...arr)

3. Ones place

Start sorting by the ones digit.

let place = 1

4. Digit loop

Continue while the largest number still has a digit at this place.

while (Math.floor(max / place) > 0)

5. Ten buckets

Decimal digits need buckets 0 through 9.

Array.from({ length: 10 }, () => [])

6. Extract digit

Divide by the current place and take the last digit.

const digit = Math.floor(value / place) % 10

7. Place in bucket

Push preserves the order of values inside each digit bucket.

buckets[digit].push(value)

8. Flatten buckets

Buckets are concatenated back into the next partially sorted array.

arr = buckets.flat()

9. Next digit

Move from ones to tens, hundreds, and beyond.

place *= 10

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Radix Sort: Visual Walkthrough & Practice · Typorithm | ApplyDjinn