Radix Sort
Sorting O(d · (n + k)) O(n + k)Sorts without comparisons: runs a stable counting pass per digit, from least to most significant.
23
7
41
15
3
34
9
28
Starting Radix Sort on 8 elements.
InvariantThe array is sorted by every digit processed so far. Because each pass is stable, earlier passes are not undone.
1/38
moves0probes0exp1i0
radix-sort.c
int getMax(int arr[], int n) {int mx = arr[0];for (int i = 1; i < n; i++)if (arr[i] > mx) mx = arr[i];return mx;}void countingPass(int arr[], int n, int exp) {int out[n], count[10] = {0};for (int i = 0; i < n; i++)count[(arr[i] / exp) % 10]++;for (int d = 1; d < 10; d++)count[d] += count[d - 1];for (int i = n - 1; i >= 0; i--)out[--count[(arr[i] / exp) % 10]] = arr[i];for (int i = 0; i < n; i++)arr[i] = out[i];}void radixSort(int arr[], int n) {for (int exp = 1; getMax(arr, n) / exp > 0; exp *= 10)countingPass(arr, n, exp);}
How Radix Sort works
Never compares elements. Sort by the least significant digit with a stable counting pass, then the next digit, and so on — earlier digits survive later passes because the passes are stable.
Best case
Few digits (small key range): effectively linear, O(d·(n+k)).
Worst case
Many digits (huge keys) make d large; memory for buckets is extra.
When to use it
Large arrays of integers or fixed-length strings with a bounded number of digits.