function radixSort(array: number[]) {const max = Math.max(...array);
for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) { const buckets: number[][] = Array.from({ length: 10 }, () => []);for (const value of array) buckets[Math.floor(value / exp) % 10].push(value);
let index = 0;
for (const bucket of buckets) for (const value of bucket) array[index++] = value;
}
}
The largest value is 98: two digits, so two passes. No comparison is ever made.
Understanding Radix sort (LSD)
The idea
Radix sort never compares two values. It distributes the values into ten buckets by their last digit, concatenates the buckets in order, then repeats with the tens digit, the hundreds, and so on. Because each pass is stable, values that tie on the current digit keep the order the previous pass gave them, so after the last pass the array is sorted by the whole number.
The cost is one read and one write per value per digit: for d-digit keys that is O(d · n), linear in n. That beats every comparison sort's n log n bound, which does not apply because no comparison is made. The price is the buckets and the requirement that keys are integers or strings of bounded length.
The four stages
Complexity
Versus its siblings
Pseudocode
RADIXSORT(array)
for each digit position, least significant first
buckets[0..9] ← empty
for each value in array, in order: append it to buckets[digit of value]
array ← buckets[0] ++ buckets[1] ++ … ++ buckets[9]
When to use
Pitfalls
History
Herman Hollerith's tabulating machines sorted punched cards this way in the 1890 US census, one digit column per pass, and radix sort predates the computer by half a century. Harold Seward wrote the first computer version with counting in 1954, the same paper that gave counting sort.