data-structures · intermediate · ~25 min
Histogram-based sorting; trade comparisons for memory.
Implement void counting_sort(int *a, size_t n, int max_val). All values are in [0, max_val]. Sort in place.
When values are small integers, counting sort beats comparison sorts by skipping comparisons entirely — O(n + k) time. It's the backbone of radix sort and many histogramming pipelines.
a[i] in [0, max_val] for all i. max_val <= 1000.
a sorted non-decreasing.
O(n + max_val) time; you may allocate O(max_val) memory.
#include <stddef.h>
void counting_sort(int *a, size_t n, int max_val) { /* TODO */ }
Forgetting to free the count array; using int for sizes that need size_t; writing back in reverse order.
n==0 returns immediately. All-equal input. Input already sorted.
Time O(n + k). Space O(k) where k = max_val + 1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.