Sorting numbers is one of the most common tasks in programming, and Radix Sort is a special sorting technique that takes a different path from traditional comparison-based algorithms. Instead of comparing two values one by one, Radix Sort groups numbers by their digits. It sorts them from the smallest place value to the largest or the other way around, depending on the variation used. This unique approach gives it a predictable and efficient structure, especially when working with large sets of integers.
with hands-on learning.
get the skills and confidence to land your next move.
Radix Sort is helpful in real projects where speed matters and the values are all within a certain numeric range. Many systems that process IDs, phone numbers, or large numeric datasets rely on this approach because it avoids heavy comparisons. For beginners learning PHP and data structures, Radix Sort provides a great lesson in thinking differently about sorting. It shows that sometimes the fastest path is not comparing elements but rearranging them by patterns.
Program 1: Basic Radix Sort in PHP
This first program introduces a simple Radix Sort using the Least Significant Digit (LSD) approach. It processes each digit from right to left until the entire list is sorted.
<?php
function getMax($arr) {
$max = $arr[0];
foreach ($arr as $value) {
if ($value > $max) {
$max = $value;
}
}
return $max;
}
function countingSortByDigit(&$arr, $exp) {
$output = array_fill(0, count($arr), 0);
$count = array_fill(0, 10, 0);
foreach ($arr as $value) {
$digit = intdiv($value, $exp) % 10;
$count[$digit]++;
}
for ($i = 1; $i < 10; $i++) {
$count[$i] += $count[$i - 1];
}
for ($i = count($arr) - 1; $i >= 0; $i--) {
$digit = intdiv($arr[$i], $exp) % 10;
$output[$count[$digit] - 1] = $arr[$i];
$count[$digit]--;
}
for ($i = 0; $i < count($arr); $i++) {
$arr[$i] = $output[$i];
}
}
function radixSort(&$arr) {
$max = getMax($arr);
for ($exp = 1; $max / $exp >= 1; $exp *= 10) {
countingSortByDigit($arr, $exp);
}
}
$data = [170, 45, 75, 90, 802, 24, 2, 66];
radixSort($data);
print_r($data);
?>This program begins by finding the largest number so it knows how many digit passes are required. It then sorts the array digit by digit, starting from the ones place. Each round produces a slightly better-ordered list until everything is fully sorted. Beginners often find this version helpful because the process is easy to visualize.
Program 2: Radix Sort With Detailed Debug Output
This version prints what happens during each digit pass. It helps you follow how the algorithm builds order step by step.
<?php
function countingSortDebug(&$arr, $exp) {
echo "Sorting by digit place: $exp\n";
$output = array_fill(0, count($arr), 0);
$count = array_fill(0, 10, 0);
foreach ($arr as $value) {
$digit = intdiv($value, $exp) % 10;
$count[$digit]++;
}
for ($i = 1; $i < 10; $i++) {
$count[$i] += $count[$i - 1];
}
for ($i = count($arr) - 1; $i >= 0; $i--) {
$digit = intdiv($arr[$i], $exp) % 10;
$output[$count[$digit] - 1] = $arr[$i];
$count[$digit]--;
}
for ($i = 0; $i < count($arr); $i++) {
$arr[$i] = $output[$i];
}
print_r($arr);
}
function radixSortDebug(&$arr) {
$max = max($arr);
for ($exp = 1; $max / $exp >= 1; $exp *= 10) {
countingSortDebug($arr, $exp);
}
}
$numbers = [329, 457, 657, 839, 436, 720, 355];
radixSortDebug($numbers);
?>This approach is great for learners who like to see each transformation. Watching how the digits guide the sorting direction makes the entire method feel less mysterious and more logical.
Program 3: Radix Sort Using Buckets
This program uses simple arrays as “buckets” to divide numbers based on digits. It gives a clearer picture of how distribution and collection work.
<?php
function radixSortBuckets(&$arr) {
$max = max($arr);
$exp = 1;
while (intdiv($max, $exp) > 0) {
$buckets = array_fill(0, 10, []);
foreach ($arr as $value) {
$digit = intdiv($value, $exp) % 10;
$buckets[$digit][] = $value;
}
$arr = [];
foreach ($buckets as $bucket) {
foreach ($bucket as $value) {
$arr[] = $value;
}
}
$exp *= 10;
}
}
$values = [15, 3, 92, 74, 58, 61, 44];
radixSortBuckets($values);
print_r($values);
?>Here the sorting feels more hands-on. Each number is placed into a bucket according to its digit, then all buckets are joined together again. This cycle repeats for every digit place. Beginners like this variation because it feels like sorting items into labeled containers.
Program 4: Recursive Radix Sort
This version uses recursion to process each digit. It shows a different structure but produces the same result.
<?php
function radixSortRecursive(&$arr, $exp, $max) {
if ($exp > $max) {
return;
}
$buckets = array_fill(0, 10, []);
foreach ($arr as $value) {
$digit = intdiv($value, $exp) % 10;
$buckets[$digit][] = $value;
}
$arr = [];
foreach ($buckets as $bucket) {
foreach ($bucket as $value) {
$arr[] = $value;
}
}
radixSortRecursive($arr, $exp * 10, $max);
}
$list = [88, 12, 105, 33, 207, 56];
$max = max($list);
radixSortRecursive($list, 1, $max);
print_r($list);
?>This recursive approach breaks the algorithm into smaller parts that call themselves until no more digits remain. It’s helpful for students who enjoy understanding tasks one layer at a time.
Program 5: Radix Sort Supporting Negative Numbers
In real applications, arrays often contain both positive and negative numbers. The classic Radix Sort only handles non-negative integers, so we need a version that works with negatives as well. This program keeps everything in one file, showing beginners how to adapt the algorithm cleanly without splitting code into multiple files.
The approach separates negative and positive numbers, sorts them individually using the usual Radix Sort logic, reverses the sorted negatives to keep proper order, and then merges them back into the original array. This keeps the function simple while extending its usability.
<?php
function radixSort(&$arr) {
if (empty($arr)) return;
// Separate negative and positive numbers
$negatives = [];
$positives = [];
foreach ($arr as $num) {
if ($num < 0) {
$negatives[] = abs($num); // Treat negative numbers as positive for sorting
} else {
$positives[] = $num;
}
}
// Radix Sort helper for non-negative numbers
$radixSortHelper = function(&$nums) {
$max = empty($nums) ? 0 : max($nums);
$exp = 1;
while ($exp <= $max) {
$buckets = array_fill(0, 10, []);
foreach ($nums as $value) {
$digit = intdiv($value, $exp) % 10;
$buckets[$digit][] = $value;
}
$nums = [];
foreach ($buckets as $bucket) {
foreach ($bucket as $value) {
$nums[] = $value;
}
}
$exp *= 10;
}
};
// Sort negatives and positives separately
$radixSortHelper($negatives);
$radixSortHelper($positives);
// Restore negative signs and reverse to correct order
$negatives = array_map(fn($x) => -$x, array_reverse($negatives));
// Merge negatives and positives
$arr = array_merge($negatives, $positives);
}
$set = [190, -23, 501, -89, 34, 10];
radixSort($set);
print_r($set);
?>When you run this code, the output is a fully sorted array with negative numbers correctly placed before positives. Beginners can clearly see the separation of concerns: negative numbers are reversed after sorting, positive numbers stay as-is, and finally everything merges together.
Program 6: Radix Sort as a Reusable Utility File
This last version shows how Radix Sort can be stored in a separate file and used anywhere in a project, which is helpful as your PHP applications get larger. It also reflects how developers often split logic into smaller, reusable pieces so that each file has a clear purpose.
<?php
// radix_sort.php
function radixSortUtil(&$arr) {
$max = max($arr);
$exp = 1;
while ($exp <= $max) {
$buckets = array_fill(0, 10, []);
foreach ($arr as $value) {
$digit = intdiv($value, $exp) % 10;
$buckets[$digit][] = $value;
}
$arr = [];
foreach ($buckets as $bucket) {
foreach ($bucket as $value) {
$arr[] = $value;
}
}
$exp *= 10;
}
}
?>Between the utility file and the main script, the idea is to keep the sorting logic completely separate from the code that uses it. This makes the sorting function easy to update or reuse without changing your main program. It is the same idea used in many real projects where organization matters, especially when the codebase starts growing.
<?php
// main.php
include 'radix_sort.php';
$set = [190, 23, 501, 89, 34, 10];
radixSortUtil($set);
print_r($set);
?>Separating the sorting logic into its own file helps you reuse it in many parts of a project. It also teaches the value of clean organization, which is something every programmer benefits from as projects get bigger.
Frequently Asked Questions (FAQ)
This section answers some of the most common questions beginners ask while learning Radix Sort.
Q1. Why does Radix Sort work mainly with numbers?
Radix Sort relies on digit positions, which makes it ideal for integers. Text can be sorted too, but it requires mapping letters to numeric values.
Q2. Is Radix Sort faster than Quick Sort?
It can be faster for large sets of integers with limited digit sizes, but it is not always the best choice for general-purpose sorting.
Q3. Does Radix Sort use comparisons?
No, it avoids comparing values directly. It groups numbers by digit, which makes it different from comparison-based algorithms.
Q4. Can Radix Sort handle negative numbers?
Basic versions do not, but advanced variants can be modified to support them.
Q5. Where is Radix Sort used in real life?
It helps in systems that sort IDs, phone numbers, fixed-length records, or large numeric datasets.
Conclusion
Radix Sort is a refreshing way to look at sorting because it focuses on digits instead of comparisons. It teaches beginners to break problems into patterns and repeated passes. Each program in this article shows a different style of Radix Sort in PHP, making it easy to explore the algorithm from many angles. With more practice, you can use these ideas to sort larger sets of data and even build your own variations. If you keep experimenting, you will gain confidence not only in PHP but also in understanding how algorithms shape the way computers handle information.




