Radix sort
Advanced · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Radix sort sorts numbers or codes one digit at a time, starting from the last digit, using a steady sort for each digit. It never compares two whole numbers, which makes it very fast for long lists of fixed-length keys like PINs.
Practical use cases
- Web app: Sorting millions of pincodes. A delivery company has 50 lakh orders to group by 6-digit pincode for route planning. Sorting by one digit at a time, six passes in all, orders the whole list without comparing complete pincodes. The planning job finishes much sooner.
- Web app: Sorting IP addresses in a security report. A security page lists failed logins by IP address. Each address is a fixed-length set of numbers, so sorting it part by part gives a clean ordered report even with millions of entries. Security staff get a list they can scan for suspicious blocks.
- System: Graphics and big integer lists. Graphics software and databases sometimes use radix sort for very large lists of fixed-size numbers. When the data doubles in size, the work only doubles too, which is why this method is a favourite for huge lists of fixed-size keys.
The story: The Post Office Pigeonholes
The mohalla post office had a wall of ten pigeonholes numbered 0 to 9. Every evening a bag of parcels arrived, each with a 3-digit sorting code, and they had to be put in order for the morning delivery.
Mrs. Sharma's niece, who worked there, did not compare parcels at all. First she dropped every parcel into the pigeonhole of its last digit, then collected them hole by hole, 0 first, 9 last. Then she did the same with the middle digit, and finally with the first digit.
"But the first pass scrambled the other digits!" said Kabir. "Look closer", she said. "When two parcels have the same digit in the current pass, they come out in the same order they went in. So the order from the earlier passes survives."
That clever trick, sorting by the least important digit first and trusting each pass to keep earlier work, is radix sort. After the last digit, the whole pile is perfectly sorted.
How to spot this problem, and where you need it
You must sort a very large list of numbers or codes that all have the same length, and you want something faster than comparing whole values against each other.
Signs you need it
- The keys are fixed-length, such as pincodes, phone numbers, dates in YYYYMMDD form, or IP addresses.
- There are millions of keys, and a general sort starts to take noticeable time.
- The problem says "sort by digits", "least significant digit" or "sort numbers without comparisons".
Where to use it in a project
- Batch jobs sorting pincodes, IDs, phone numbers or dates before grouping or reporting.
- Network and security tools ordering IP addresses or timestamps in large logs.
The solution
Start with the last digit. Sort the whole list by that digit only, using a steady sort such as counting sort so equal digits keep their order. Then sort again by the second-to-last digit, and so on until the first digit. Because each pass keeps the order from earlier passes for ties, after the final pass the full list is in order.
Payoff: Before: comparing whole 6-digit codes across 50 lakh orders. After: 6 quick passes, each touching every item once.
Explain it like I am 8
To sort big numbers, sort them by their last digit first. Then sort them again by the middle digit, being careful to keep numbers in the same order if their digits match. Finally sort by the first digit. Magic: it is sorted!
How it works, step by step
- Find the biggest number to learn how many digits it has.
- Pass 1: put every number into one of 10 buckets by its last (ones) digit, then read the buckets 0 to 9.
- Pass 2: repeat with the tens digit, but keep numbers with the same digit in the order they arrive (stable).
- Continue with hundreds, thousands, and so on, up to the biggest number's digits.
- After the last digit pass, the list is fully sorted.
The code in four languages
PHP
<?php
// Radix sort (least significant digit first) for non-negative integers.
function radixSort(array $a): array {
if (!$a) return [];
$max = max($a);
for ($exp = 1; intdiv($max, $exp) > 0; $exp *= 10) {
$buckets = array_fill(0, 10, []); // ten pigeonholes
foreach ($a as $v) {
$digit = intdiv($v, $exp) % 10; // the digit for this pass
$buckets[$digit][] = $v; // appending keeps earlier order (stable)
}
$a = array_merge(...$buckets); // read the holes 0..9
}
return $a;
}
echo implode(', ', radixSort([329, 457, 657, 839, 436, 720, 355]));
// 329, 355, 436, 457, 657, 720, 839JavaScript
// Radix sort (least significant digit first) for non-negative integers.
function radixSort(input) {
let a = [...input];
if (a.length === 0) return a;
const max = Math.max(...a);
for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) {
const buckets = Array.from({ length: 10 }, () => []); // ten pigeonholes
for (const v of a) {
const digit = Math.floor(v / exp) % 10; // the digit for this pass
buckets[digit].push(v); // pushing keeps earlier order (stable)
}
a = [].concat(...buckets); // read the holes 0..9
}
return a;
}
console.log(radixSort([329, 457, 657, 839, 436, 720, 355]).join(', '));
// 329, 355, 436, 457, 657, 720, 839Java
import java.util.*;
import java.util.stream.*;
public class Main {
// Radix sort (least significant digit first) for non-negative integers.
static int[] radixSort(int[] input) {
int[] a = Arrays.copyOf(input, input.length);
if (a.length == 0) return a;
int max = Arrays.stream(a).max().getAsInt();
for (int exp = 1; max / exp > 0; exp *= 10) {
List<List<Integer>> buckets = new ArrayList<>();
for (int d = 0; d < 10; d++) buckets.add(new ArrayList<>()); // ten pigeonholes
for (int v : a) {
int digit = (v / exp) % 10; // the digit for this pass
buckets.get(digit).add(v); // adding at the end keeps earlier order (stable)
}
int pos = 0; // read the holes 0..9
for (List<Integer> bucket : buckets) {
for (int v : bucket) a[pos++] = v;
}
}
return a;
}
// Joins the numbers with a separator, e.g. "1, 2, 3".
static String join(int[] a, String sep) {
return Arrays.stream(a).mapToObj(String::valueOf).collect(Collectors.joining(sep));
}
public static void main(String[] args) {
System.out.println(join(radixSort(new int[]{329, 457, 657, 839, 436, 720, 355}), ", "));
// 329, 355, 436, 457, 657, 720, 839
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// Radix sort (least significant digit first) for non-negative integers.
func radixSort(input []int) []int {
a := append([]int(nil), input...)
if len(a) == 0 {
return a
}
max := a[0]
for _, v := range a {
if v > max {
max = v
}
}
for exp := 1; max/exp > 0; exp *= 10 {
buckets := make([][]int, 10) // ten pigeonholes
for _, v := range a {
digit := (v / exp) % 10 // the digit for this pass
buckets[digit] = append(buckets[digit], v) // appending keeps earlier order (stable)
}
next := []int{}
for _, b := range buckets { // read the holes 0..9
next = append(next, b...)
}
a = next
}
return a
}
// join glues the numbers together with a separator, e.g. "1, 2, 3".
func join(a []int, sep string) string {
parts := make([]string, len(a))
for i, v := range a {
parts[i] = strconv.Itoa(v)
}
return strings.Join(parts, sep)
}
func main() {
fmt.Println(join(radixSort([]int{329, 457, 657, 839, 436, 720, 355}), ", "))
// 329, 355, 436, 457, 657, 720, 839
}Time: O(d × (n + k)) · Extra space: O(n + k). d is the number of digits and k is 10 for decimal digits. With a fixed small d, that is essentially a straight line in n.
Watch out for
- Starting from the most significant digit with this simple version. Least significant first is what makes the stable passes work.
- Using an unstable step per digit. That destroys the order built by earlier passes.
- Forgetting it needs whole numbers (or strings of fixed length); negative numbers need extra handling.
Quick check
- Which digit does LSD radix sort process first?
- The first (biggest place) digit
- The last (ones) digit
- The middle digit
- Why must each digit pass be stable?
- To save memory
- To make it recursive
- So equal digits keep the order created by earlier passes
- How many passes does radix sort need for numbers up to 9,999?
- Four
- One
- Ten