Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F103, STM32F407, STM32G031 · level intermediate · 9 min read
Open in the interactive handbook

76з. Radix sort and counting sort: 8- and 16-bit keys and the memory cost

All the sorts from 76б compare elements with each other, and that way you cannot sort in fewer than n log n comparisons. But firmware keys are usually short: a byte, a 12-bit ADC sample, an 11-bit CAN identifier. Such keys need not be compared but can be distributed into buckets — by value or by digits. The work then grows linearly with n, and the price is paid in memory: counters and a second array. This section is about where that deal pays off on a small chip and where it does not.

Basis: alg.c with counting sort, radix sort by 8 and by 4 bits and a histogram median, built with gcc 12.2.0 on the computer (stm-sys:1) — the result is checked against the library qsort, stability is checked on records with indices, and for comparison Shell sort from 76б was run on the same data. The same file built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0 — function sizes and stack frames. Work is expressed as the number of element accesses and comparisons, not cycles.

Terms used in the documentation

Original Meaning
counting sort counting sort: count each value and place them by position
radix sort, LSD radix sort starting from the least significant digit
digit, radix (base) of a pass the digit and the base of a pass: how many key bits are taken at once
bucket, histogram bucket, histogram: how many times each value occurred
prefix sum running sum: where the place of each bucket begins
sign-bit flip flipping the top bit to sort signed values as unsigned
comparison sort lower bound the n log n lower bound for comparison sorts

In plain words. A postman does not compare letters with each other — he puts them into pigeonholes numbered by house. If there are few houses, this is faster than any "who comes first" sort. But each number needs its own pigeonhole: a hundred houses — a hundred pigeonholes, a thousand — a thousand. Radix sort is smarter: first it distributes by the last digit of the number, then by the one before — and only ten pigeonholes are needed.


76з.1 Counting sort

The keys are bytes, there are only 256 values. The first pass counts how many times each value occurred; then the running sum turns the counters into the starts of places; the second pass places the elements:

void count_sort_u8(const uint8_t *in, uint8_t *out, unsigned n)
{
    uint16_t cnt[256];
    memset(cnt, 0, sizeof cnt);
    for (unsigned i = 0; i < n; i++)
        cnt[in[i]]++;
    unsigned sum = 0;
    for (unsigned d = 0; d < 256; d++) {
        unsigned c = cnt[d];
        cnt[d] = (uint16_t)sum; /* начало места для ключа d */
        sum += c;
    }
    for (unsigned i = 0; i < n; i++)
        out[cnt[in[i]]++] = in[i];
    TOUCH(3 * n);
}

Not a single key comparison: n reads for counting, n reads and n writes for placement, plus 256 steps over the counters. Placement goes from left to right, so equal keys keep their order — the sort is stable, and this will be needed in radix sort. TOUCH counts element accesses on the computer, in firmware it is empty.

The price is memory. 256 uint16_t counters are 512 bytes, and in this function they live on the stack: -fstack-usage showed a 528-byte frame on M4. On a chip with 2 KB of RAM and a 1 KB task stack that is half the stack. The counters are made static or are taken from a shared work buffer.


76з.2 Why a 12-bit ADC cannot be counting-sorted directly

12-bit samples need 4096 buckets — 8192 bytes of counters. That is more than all the RAM of a small chip and 16 times more than the 256 samples themselves. Counting is good when there are few values: bytes, channel numbers, status codes. For longer keys — radix sort.


76з.3 LSD radix sort

The key is cut into digits of a few bits and sorted by counting first by the least significant digit, then by the next one — and so on up to the most significant. This works only because each pass is stable: the order established by the lower digits is kept among equal higher ones.

Eight keys 0x3A, 0x17, 0xA3, 0x1F, 0x3C, 0xA0, 0x71, 0x13: after the first pass they are ordered by the low hexadecimal digit, after the second by the high one, and the whole column is ordered; 0x13 and 0x17 come in this order after the first pass and keep it

One pass is the same counting sort, only by a digit:

memset(cnt, 0, digits * sizeof cnt[0]);
for (unsigned i = 0; i < n; i++)
    cnt[(a[i] >> shift) & mask]++;
for (unsigned i = 0; i < n; i++)
    tmp[cnt[(a[i] >> shift) & mask]++] = a[i];

For 16-bit keys there are two variants:

void radix_u16_8(uint16_t *a, uint16_t *tmp, unsigned n)
{
    static uint16_t cnt[256];
    radix_pass(a, tmp, n, 0, 8, cnt);
    radix_pass(tmp, a, n, 8, 8, cnt);
}
void radix_u16_4(uint16_t *a, uint16_t *tmp, unsigned n)
{
    uint16_t cnt[16];
    radix_pass(a, tmp, n, 0, 4, cnt);
    radix_pass(tmp, a, n, 4, 4, cnt);
    radix_pass(a, tmp, n, 8, 4, cnt);
    radix_pass(tmp, a, n, 12, 4, cnt);
}

The number of passes is even, so the result returns to the original array. An 8-bit digit means two passes and 512 bytes of counters; a 4-bit digit means four passes and 32 bytes of counters, which live comfortably on the stack.


76з.4 How much work and how much memory

256 random 12-bit samples, the result checked against qsort:

Method work RAM beyond the array
radix by 8 bits 1536 element accesses, 2 passes 512-byte buffer + 512 bytes of counters
radix by 4 bits 3072 accesses, 4 passes 512-byte buffer + 32 bytes of counters
Shell from 76б 2465 comparisons and 1292 moves none

On 1000 random 16-bit keys the gap grows: radix by 8 bits takes 6000 accesses, Shell 12952 comparisons and 6646 moves. Radix sort is linear: 3 accesses per element per pass, the same for any input, — and its time is as predictable as that of the networks from 76в. Shell grows faster than n.

But at small n the overhead is noticeable: each 8-bit pass clears and walks 256 counters, that is 512 extra steps for two passes at 256 elements. Element accesses and comparisons are different operations, and an honest comparison in time comes only from a measurement on silicon (73). The threshold from which radix sort pays off lies in the hundreds of elements, and below it — Shell or insertion.

The main limitation is memory. A buffer of n elements plus counters: for 256 samples by 8 bits — 1024 bytes, by 4 bits — 544. With 2 KB of RAM that is from a quarter to half of all memory; Shell needs nothing extra.


76з.5 Signed keys

Samples of a differential ADC or a temperature are signed numbers. In two's complement negative numbers have the top bit set, and as unsigned they are greater than positive ones. The run: 256 numbers from −2000 to 2000, sorted as unsigned — the negative ones started only at element s[127], after all the positive ones. The cure is one action: flip the top bit before sorting and back afterwards:

for (unsigned i = 0; i < n; i++)
    u[i] ^= 0x8000u;

After the flip −2000…−1 become 0x7830…0x7FFF, and 0…2000 become 0x8000…0x87D0, and the unsigned order matches the signed one. With the flip the run gave the correct order.


76з.6 A median without sorting

If only the median is needed — for example, of 8-bit samples over a second — there is no need to sort at all: a histogram and a pass over the running sum up to the half:

unsigned need = n / 2 + 1, acc = 0;
for (unsigned d = 0; d < 256; d++) {
    acc += cnt[d];
    if (acc >= need)
        return (uint8_t)d;
}

On 1001 samples with outliers the histogram median is 124, the same as the middle element after a full sort. The work is n for the histogram plus no more than 256 steps, the memory is the same 512 bytes of counters. For a sliding window of 5–9 samples this does not fit — there the networks from 76в are used — but for a median over a long interval it fits best of all.


76з.7 Records, not just keys

In practice what is sorted is not bare numbers but records: a CAN frame by identifier, an event by code. Radix sort moves the whole record and takes the key from its field — and stability is the main property here: records with an equal key stay in the order of arrival. The run: 256 records with a key of 0…7 in the high byte and a sequence number in the low byte kept, after a pass by key, the numbers increasing within each key.

For large records moving them is expensive; then an array of indices is sorted by key, and the records are not moved.


76з.8 Code and stack

Function code bytes M4 stack frame M4 code bytes M0 stack frame M0
count_sort_u8 114 528 112 536
radix_pass 156 32 146 32
radix_u16_8 56 32 60 32
radix_u16_4 84 64 90 64
hist_median_u8 110 528 112 528

The 528-byte frames of count_sort_u8 and hist_median_u8 are the array of counters on the stack. In radix_u16_8 the counters are static, and the frame is 32 bytes; in radix_u16_4 16 counters on the stack gave a 64-byte frame.


76з.9 Pitfalls

Counting sort crashed the stack. 256 uint16_t counters on the stack mean a 528-byte frame; in a task with a 512-byte stack that is an overflow on the first call. The counters — static or in a shared buffer.

The negative values ended up at the end. Signed keys were sorted as unsigned: the negative ones started at s[127] of 256. Flip the top bit before and after.

Radix sort mixed up equal keys. One of the passes was unstable — placement went from right to left without counting places backwards. The passes must be stable, otherwise the lower digits are lost.

12-bit samples are sorted by counting. 4096 counters are 8 KB. Radix sort by 4 or 8 bits.

The result ended up in the temporary buffer. The number of passes is odd. The number of passes is even, or a copy at the end.


76з.10 Summary

Next: section 76и "Recursion and the stack on a microcontroller: depth, -fstack-usage and conversion to iteration" — why a recursive flood fill needs tens of kilobytes of stack and how to rewrite it onto an own stack with a known limit.

Open in the interactive handbook