Counting and radix sort
25 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Counting sort and radix sort achieve linear time by indexing directly rather than comparing pairs.
The Comparison Lower Bound
A stable sort keeps elements with equal keys in the same order they had before sorting.
Every comparison sort compares two elements using less-than or greater-than operators. A decision tree models all possible comparison outcomes for n items. To sort n distinct elements, the tree must have at least n factorial leaf nodes. Each leaf represents a distinct permutation of the input elements.
The height of a binary tree with n factorial leaves is at least log₂(n factorial). By Stirling's approximation, log₂(n factorial) is approximately n log₂(n) - 1.44n. Therefore, any comparison sort requires at least O(n log n) operations in the worst case. No comparison algorithm can ever break this mathematical barrier.
To sort faster than O(n log n), an algorithm must avoid pairwise comparisons. Non-comparison sorts inspect the digits or integer keys directly. They use key values as array indices to place items in linear O(n) time.
Counting Sort Mechanics
Counting sort is a non-comparison sort that counts how often each key occurs and uses the counts to place every value directly, in O(n + k) time.
Counting sort counts how many times each key occurs, turns the counts into positions, then places every value directly. The program below sorts seven numbers.
Example 1 · Stable Counting Sort
import java.util.Arrays;
public class CountingSortDemo { public static int[] countingSort(int[] arr) { if (arr.length == 0) return arr; int min = arr[0], max = arr[0]; for (int v : arr) { if (v < min) min = v; if (v > max) max = v; } int range = max - min + 1; int[] count = new int[range]; for (int v : arr) count[v - min]++; for (int i = 1; i < range; i++) count[i] += count[i - 1];
int[] output = new int[arr.length]; for (int i = arr.length - 1; i >= 0; i--) { int val = arr[i]; output[--count[val - min]] = val; } return output; }
public static void main(String[] args) { int[] arr = {4, -2, 2, 8, 3, 3, 1}; int[] sorted = countingSort(arr); System.out.println(Arrays.toString(sorted)); }}[-2, 1, 2, 3, 3, 4, 8]
What this code does
- Finds minimum and maximum to determine the required count array range.
- Offsets indices by min so negative values are handled correctly.
- Accumulates prefix sums to find target output indices.
It allocates a frequency array count of size k + 1. First, it scans the input and increments count[x] for each item x. Then, it converts counts into prefix sums to store starting output positions. Next, it traverses the input in reverse to place items stably. Placing elements backwards into an output array preserves the relative order of duplicates. The time complexity is O(n + k), and auxiliary space is O(n + k). When the range k is proportional to n, counting sort runs in linear O(n) time. Consider tracing counting sort on array [4, 2, 2, 3]: Frequencies: count[2] = 2, count[3] = 1, count[4] = 1. Prefix sums: count[2] = 2, count[3] = 3, count[4] = 4. Reverse scan places 3 at index 2, and 2 at index 1. It places duplicate 2 at index 0, and 4 at index 3, yielding [2, 2, 3, 4].
Predict the output
Predict the positions
Read each snippet and pick what it prints.
Radix Sort and Bucket Sort
Radix sort sorts numbers digit by digit with a stable counting sort, and bucket sort spreads decimals into buckets. The examples show both.
Example 2 · Least Significant Digit Radix Sort
import java.util.Arrays;
public class RadixSortDemo { public static void radixSort(int[] arr) { if (arr.length <= 1) return; int max = arr[0]; for (int v : arr) if (v > max) max = v;
for (int exp = 1; max / exp > 0; exp *= 10) { countingSortByDigit(arr, exp); } }
private static void countingSortByDigit(int[] arr, int exp) { int n = arr.length; int[] output = new int[n]; int[] count = new int[10];
for (int i = 0; i < n; i++) { int digit = (arr[i] / exp) % 10; count[digit]++; } for (int i = 1; i < 10; i++) count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--) { int digit = (arr[i] / exp) % 10; output[--count[digit]] = arr[i]; } System.arraycopy(output, 0, arr, 0, n); }
public static void main(String[] args) { int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; radixSort(arr); System.out.println(Arrays.toString(arr)); }}[2, 24, 45, 66, 75, 90, 170, 802]
What this code does
- Finds the maximum value to determine the maximum number of decimal digits.
- Iterates over digit places 1, 10, 100 with multiplier exp.
- Applies counting sort to the current digit with base 10.
Example 3 · Bucket Sort for Unit Interval Numbers
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class BucketSortDemo { public static void bucketSort(float[] arr) { int n = arr.length; if (n <= 1) return;
List<Float>[] buckets = new ArrayList[n]; for (int i = 0; i < n; i++) buckets[i] = new ArrayList<>();
for (float v : arr) { int bucketIdx = (int) (v * n); buckets[bucketIdx].add(v); }
for (int i = 0; i < n; i++) { Collections.sort(buckets[i]); }
int idx = 0; for (int i = 0; i < n; i++) { for (float v : buckets[i]) { arr[idx++] = v; } } }
public static void main(String[] args) { float[] arr = {0.78f, 0.17f, 0.39f, 0.26f, 0.72f, 0.94f, 0.21f}; bucketSort(arr); StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(String.format("%.2f", arr[i])).append(i == arr.length - 1 ? "" : " "); } System.out.println(sb.toString()); }}0.17 0.21 0.26 0.39 0.72 0.78 0.94
What this code does
- Creates n empty buckets for n floating point numbers.
- Maps each float value into bucket index floor(v * n).
- Sorts individual buckets containing few items.
Radix sort solves this by sorting numbers digit by digit. It starts at the least significant digit and moves to the most significant. Each digit pass runs a stable counting sort with base b (such as base 10). Because each digit pass is stable, earlier digit orderings are preserved. For d digits and base b, radix sort runs in O(d * (n + b)) time. For fixed-length integers, d is a constant, yielding linear O(n) performance. Radix sort sorts large integer collections efficiently without comparisons. Bucket sort partitions numbers into a fixed number of buckets over interval [0, 1). It maps each floating-point value to a bucket index using multiplication. Individual buckets are sorted using insertion sort, then concatenated. When input is uniformly distributed, bucket sort runs in expected linear O(n) time.
Predict the output
Predict the digits
Read the snippet and pick what it prints.
Next step
Check your understanding
10 quick questions