PHP Radix Sort Algorithm
last modified November 25, 2026
Radix sort is a non-comparison sorting algorithm that distributes values into buckets by one digit at a time. For n values with at most k digits it runs in O(nk) time and needs O(n) extra memory, and it is stable.
This article implements radix sort in PHP for integers and strings, handles negative numbers, demonstrates the stability that the algorithm depends on, and lists the cases where a comparison sort is the better choice.
How radix sort works
Radix sort is a non-comparison sorting algorithm. Instead of comparing pairs of values, it distributes the input into buckets according to one digit of each value, collects the buckets in order, and repeats with the next digit. For decimal integers there are ten buckets, one for each digit.
The passes start with the least significant digit. That order matters: after the pass over the most significant digit the array is sorted, and the earlier passes only have to preserve the relative order of values whose current digit is equal. The collection step must therefore be stable, which is easy with buckets: values are appended in the order they are visited, and merging the buckets keeps that order.
With n values and at most k digits, the algorithm performs k passes over the array and runs in O(nk) time. The extra memory is O(n + b), where b is the number of buckets. Each pass is a stable counting sort of one digit, and the counting sort tutorial builds that subroutine from scratch.
The same idea works for any key that can be split into fixed-width parts: characters of a string, bytes of a binary value, or groups of bits. Merging the buckets from the highest index down to zero produces descending order, because the collection order is reversed while the order inside each bucket is preserved.
Sorting numbers
The first example sorts non-negative integers in base ten. The outer loop runs once per digit position, and the inner loop distributes the values into the ten buckets.
<?php
declare(strict_types=1);
function radixSort(array $items): array
{
$max = max($items);
$place = 1;
while (intdiv($max, $place) > 0) {
$buckets = array_fill(0, 10, []);
foreach ($items as $item) {
$digit = intdiv($item, $place) % 10;
$buckets[$digit][] = $item;
}
$items = array_merge(...$buckets);
$place *= 10;
}
return $items;
}
$numbers = [170, 45, 75, 90, 802, 24, 2, 66];
echo implode(", ", radixSort($numbers)), "\n";
max gives the largest value, so the loop can stop when $place has passed it. The digit is extracted with intdiv($item, $place) % 10 rather than with a floating-point division, which avoids rounding problems for large numbers. array_merge(...$buckets) flattens the ten buckets in index order, and that single call replaces the whole collection loop. The input must not be empty, because max would fail.
$ php radix_basic.php 2, 24, 45, 66, 75, 90, 170, 802
Sorting strings
A string is a sequence of digits in base 256. The passes go from the last character to the first, and each character becomes a bucket index from 0 to 255.
<?php
declare(strict_types=1);
function radixSortStrings(array $words): array
{
$width = max(array_map('strlen', $words));
for ($pos = $width - 1; $pos >= 0; $pos--) {
$buckets = array_fill(0, 256, []);
foreach ($words as $word) {
$key = $pos < strlen($word) ? ord($word[$pos]) : 0;
$buckets[$key][] = $word;
}
$words = array_merge(...$buckets);
}
return $words;
}
$words = ["figs", "apple", "fig", "pear"];
echo implode(", ", radixSortStrings($words)), "\n";
ord converts the current character to its byte value. A word that has no character at the current position is placed in bucket 0, and every real ASCII character sorts above it, so a prefix comes before its extensions: fig before figs. The table has 256 entries because the code works on bytes; text in UTF-8 needs the mb_* functions and a larger bucket table, or a conversion to code points first.
$ php radix_strings.php apple, fig, figs, pear
Negative numbers
The digit extraction assumes non-negative values. Signed integers are handled by splitting the input, sorting the absolute values, and putting the negative part back in reverse order. The listing repeats radixSort from the first example so that it stays a complete script.
<?php
declare(strict_types=1);
function radixSort(array $items): array
{
$max = max($items);
$place = 1;
while (intdiv($max, $place) > 0) {
$buckets = array_fill(0, 10, []);
foreach ($items as $item) {
$digit = intdiv($item, $place) % 10;
$buckets[$digit][] = $item;
}
$items = array_merge(...$buckets);
$place *= 10;
}
return $items;
}
function radixSortSigned(array $items): array
{
$negative = [];
$positive = [];
foreach ($items as $item) {
if ($item < 0) {
$negative[] = -$item;
} else {
$positive[] = $item;
}
}
$negative = array_reverse(radixSort($negative));
return [...array_map(fn(int $n): int => -$n, $negative), ...radixSort($positive)];
}
$numbers = [42, -7, 0, 15, -120, 3];
echo implode(", ", radixSortSigned($numbers)), "\n";
The negative values are made positive before the sort, so the algorithm sees ordinary digits. Reversing the sorted negatives turns ascending order of absolute values into descending order of the original values, and negating them restores the signs. The positive part, including zero, is appended unchanged. The split costs O(n) extra memory, which is the usual price for handling signed keys with radix sort.
$ php radix_negative.php -120, -7, 0, 3, 15, 42
Stability
Radix sort is stable: values with equal keys keep their original relative order. The next example sorts records by an integer identifier and shows which record comes first when two identifiers are equal.
<?php
declare(strict_types=1);
function radixSortRecords(array $records): array
{
$max = max(array_column($records, 'id'));
$place = 1;
while (intdiv($max, $place) > 0) {
$buckets = array_fill(0, 10, []);
foreach ($records as $record) {
$digit = intdiv($record['id'], $place) % 10;
$buckets[$digit][] = $record;
}
$records = array_merge(...$buckets);
$place *= 10;
}
return $records;
}
$records = [
['id' => 23, 'name' => 'a'],
['id' => 11, 'name' => 'b'],
['id' => 23, 'name' => 'c'],
['id' => 11, 'name' => 'd'],
];
$sorted = array_map(
fn(array $record): string => $record['id'] . $record['name'],
radixSortRecords($records)
);
echo implode(" ", $sorted), "\n";
The two records with id 11 appear as 11b and then 11d, and the two records with id 23 appear as 23a and then 23c, exactly as in the input. No pass ever reorders values that land in the same bucket. This property is not a bonus: the least-significant-digit algorithm depends on it, because each pass must preserve the order produced by the previous one.
$ php radix_stable.php 11b 11d 23a 23c
When to use radix sort
Radix sort wins when the keys are fixed-width and the number of digits is small compared with the number of values.
- Fixed-width integer keys: identifiers, timestamps, and scores are natural candidates.
- Large inputs: O(nk) with a small k beats O(n log n) when n is large.
- Stable output: equal keys keep their order without extra work.
- Limited key range: the bucket count must stay small; a wide key space needs more memory.
- Floating-point numbers: not supported directly, because their bit patterns do not order like integers.
- Everyday PHP: prefer
sortandusort; they handle mixed types and are written in C.
Source
This article covered radix sort in PHP: the least-significant-digit idea, integer and string keys, negative numbers, stability, and the limits of the algorithm. See also the PHP counting sort, bucket sort, quick sort, and merge sort tutorials.
Author
List all PHP tutorials.