data-structures · intermediate · ~25 min
Histogram-based sorting; trade comparisons for memory.
Sort an array of small non-negative integers using counting sort.
Implement void counting_sort(int *a, size_t n, int max_val) that sorts the n elements of a into non-decreasing order, in place. Every value is in the range [0, max_val].
a: writable array of n ints, each in [0, max_val].n: the number of elements.max_val: the largest possible value (max_val <= 1000).Nothing returned; a[0..n-1] is sorted in place.
{3,1,4,1,5,9,2,6,5,3,5}, max_val=9 -> {1,1,2,3,3,4,5,5,5,6,9}
{0,0,0,1,1,1}, max_val=1 -> {0,0,0,1,1,1}
n == 0 returns immediately.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: n ints each in [0, max_val]; n; max_val (<= 1000).
Nothing returned; a is sorted non-decreasing in place.
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.