Radix sort (least-significant-digit first) sorts integers one digit at a time, from the ones place upward, using a stable counting sort for each digit. Stability is essential: it preserves the order from earlier digits. With d digits it runs in O(d(n + b)) for base b, which is linear for fixed-width keys.
Remember
for (exp = 1; max / exp > 0; exp *= 10)
stable_count_sort_by_digit(a, n, exp); /* (x / exp) % 10 */
Reference
Cheat Sheet
Keep these facts handy while you work with Radix Sort in C.
#include <stdio.h>
static void count_by_digit(int a[], int n, int exp) {
int out[16], cnt[10] = {0};
for (int i = 0; i < n; i++) cnt[(a[i] / exp) % 10]++;
for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];
for (int i = n - 1; i >= 0; i--) out[--cnt[(a[i] / exp) % 10]] = a[i];
for (int i = 0; i < n; i++) a[i] = out[i];
}
int main(void) {
int a[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = 8, max = 802;
for (int exp = 1; max / exp > 0; exp *= 10) {
count_by_digit(a, n, exp);
printf("exp %d:", exp);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
return 0;
}
Pass 1 orders by the ones digit; 170 and 90 (digit 0) keep their original relative order.
Pass 2 orders by the tens digit, grouping 802 and 2 (tens digit 0) first.
Pass 3 orders by the hundreds digit and the array is fully sorted.
Edge Cases & Pitfalls
Check these before relying on Radix Sort in real programs.
stable
Unstable digit sort
If the per-digit sort is not stable, earlier digit work is lost.
neg
Negative numbers
Handle signs separately or offset the keys.
Remember
Key Takeaways
Digit by digit, low to high.
Needs a stable inner sort.
Linear for fixed-width keys.
One line: Radix sort (least-significant-digit first) sorts integers one digit at a time, from the ones place upward, using a stable counting sort for each digit.
Frequently Asked Questions
It sorts numbers by one digit at a time, from least to most significant, using a stable sort for each digit.
Because the order established by lower digits must be preserved when sorting by higher digits.
Continue with "Comparing Sorting Algorithms in C" next. Count comparisons and moves for three simple sorts on the same input. The C Sorting Algorithms hub lists every topic in order.