76б. Sorting on a microcontroller: insertion, Shell, quicksort without recursion, merge and an ADC median filter
In section 76 bubble sort appeared only as an example of O(n²). Here are four sorts that really occur in firmware, and the question of which one to take when there are only 2 KB of RAM and the processing time must be predictable: not "usually fast" but "never slower than". At the end comes the ADC median filter, the most common place where a device sorts anything at all.
Basis: one file alg.c with four sorts and the filter, built with gcc
12.2.0 on the computer (stm-sys:1) — there the sorts count comparisons and
moves on six kinds of input; the same file built with arm-none-eabi-gcc 12.2.1
(stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0 — that gives function sizes and
stack frames from -fstack-usage. Cycles on silicon were not measured: time in
this section is expressed as the number of comparisons and moves, an honest measure for
comparing algorithms with each other, but not microseconds.
Terms used in the documentation
Original Meaning insertion sort insertion sort Shellsort, gap sequence Shell sort, the sequence of gaps quicksort, pivot quicksort, the pivot element median-of-three median of three: the pivot is the middle of the first, middle and last merge sort, bottom-up merge sort, bottom-up without recursion stable sort stable sort: equal keys keep their order in-place in place: without a second array sliding median sliding median: the median of the last N samples In plain words. To sort means to put things in order, like cards in a hand. On a computer you take the ready
qsortand do not think. On a microcontroller you have to think: memory is scarce, there is no spare array, and a handler that fitted in a millisecond yesterday can take a hundred today on unlucky data. So you choose not the sort that is fastest "on average" but the one whose worst case is known and tolerable.
76б.1 What firmware expects from a sort
Three requirements that a program on a computer does not have:
| Requirement | Why | What it rules out |
|---|---|---|
| memory beyond the array — tens of bytes | 2–20 KB of RAM for everything | merge with a buffer of n elements |
| a known worst case | the sort runs inside a control loop | naive quicksort: n² on sorted input |
| no deep recursion | the task stack is 256–1024 bytes | recursive quicksort and recursive merge |
Sometimes a fourth is needed — stability: equal keys stay in the order in which they arrived. For example, events are sorted by priority, and among equal ones the order of arrival should be kept. Insertion and merge are stable, Shell and quicksort are not.
All measurements below are on an array of 256 int16_t numbers (512 bytes) and six
inputs: random, already sorted, reversed, all elements equal, only
four distinct values and a "pyramid" — rising up to the middle, then falling.
A comparison is counted by the LESS macro: in firmware it is just <, on the
computer it also increments a counter. The lines with the move counter
MOVED are omitted from the listings.
76б.2 Insertion: the best choice for small and nearly sorted arrays
Take the next element and shift it left while the left neighbour is larger:
void sort_insert(int16_t *a, size_t n)
{
for (size_t i = 1; i < n; i++) {
int16_t v = a[i];
size_t j = i;
while (j > 0 && LESS(v, a[j - 1])) {
a[j] = a[j - 1];
j--;
}
a[j] = v;
}
}
On sorted input it is 255 comparisons and not a single move: one pass. On reversed input it is n(n − 1)/2 = 32640 comparisons. A factor of 128 between the best and the worst case is exactly what must not happen in a control loop. On the other hand the code is tiny: 68 bytes on Cortex-M4, 60 bytes on Cortex-M0, a stack frame of 12 bytes. Insertion is good when there are a dozen or two elements or when the array is nearly sorted: a new sample was added to an already sorted list. That is why quicksort and Shell use it for short pieces too.
76б.3 Shell: insertion with a large gap
Shell sort is the same insertion, but first over elements a large gap apart, then a smaller one, and the last pass uses a gap of 1. Distant elements quickly move to their place, and the last pass runs over a nearly sorted array.
static const uint16_t GAPS[] = {701, 301, 132, 57, 23, 10, 4, 1};
for (size_t g = 0; g < sizeof GAPS / sizeof GAPS[0]; g++) {
size_t h = GAPS[g];
for (size_t i = h; i < n; i++) {
int16_t v = a[i];
size_t j = i;
while (j >= h && LESS(v, a[j - h])) {
a[j] = a[j - h];
j -= h;
}
a[j] = v;
}
}
The gaps are taken from Ciura's sequence — it was found by search and works well up to one and a half thousand elements. On 256 elements the worst of the six inputs is 2490 comparisons, the best is 1309: the spread is less than a factor of two. No recursion, no memory beyond the array, the code is 120 bytes on M4. For firmware this is often the best compromise: predictable, short and insensitive to unlucky inputs. Shell sort has no exact worst-case formula, so the predictability here is measured, not proven.
76б.4 Quicksort without recursion and with a depth limit
Quicksort splits the array around a pivot into "less" and "greater" and sorts the parts. It has two problems on a microcontroller.
Problem one — the pivot. If the first element is taken and the input is already sorted, each split cuts off a single element. The naive version on a sorted array of 256 numbers made 32640 comparisons — as many as insertion on the worst input — and recursed to a depth of 255. The frame of this function on M4 is 40 bytes, so the stack is 255 × 40 = 10200 bytes: five times the entire RAM of a small chip. On random input the same function cost 2148 comparisons and a depth of 17 — which is why its flaw is not visible on the bench.
The cure is median of three: the pivot is the middle in value of the first, middle and last elements. At the same time these three are put in place and serve as sentinels for the partition loops:
size_t mid = lo + (hi - lo) / 2;
if (LESS(a[mid], a[lo])) swap16(&a[mid], &a[lo]);
if (LESS(a[hi - 1], a[lo])) swap16(&a[hi - 1], &a[lo]);
if (LESS(a[hi - 1], a[mid])) swap16(&a[hi - 1], &a[mid]);
int16_t p = a[mid];
Problem two — recursion. It is replaced by an own stack of bounds, and the main rule is: handle the smaller part at once, postpone the larger one. Then there are never more than log₂ n postponed pieces: each next one is at least half the size of the previous one.
if (cut - lo < hi - cut) {
lo_st[sp] = cut; hi_st[sp] = hi; dp_st[sp] = (uint8_t)depth; sp++;
hi = cut;
} else {
lo_st[sp] = lo; hi_st[sp] = cut; dp_st[sp] = (uint8_t)depth; sp++;
lo = cut;
}
A stack of 16 bound pairs is enough for up to 65 536 elements. On six inputs of 256 elements it never held more than 4 pieces at once.
Median of three does not save from every input: the "pyramid" gave 3767 comparisons against 2385 on random input. There are also inputs specially crafted against median of three — on them it is n² again. So the third defence is a depth limit: if more than 2·log₂ n splits were made on one branch, the piece is finished by Shell sort. Such a mix is called introspective sort (libraries use heapsort instead of Shell, 76г). Pieces shorter than 16 elements are not split at all — at the end one insertion pass finishes them.
The cost: 368 bytes of code on M4 (plus the calls to Shell and insertion) and a 200-byte frame — the whole bounds stack lives in the frame.
76б.5 Merge: stable and even, but with a buffer
Bottom-up merge sort does without recursion: first pairs of neighbouring elements are merged, then pairs of 2, of 4 and so on.
while (i < mid && j < hi)
tmp[k++] = LESS(a[j], a[i]) ? a[j++] : a[i++];
This is the most even sort of the four: from 1024 to 1712 comparisons on any
input, exactly 4096 moves always — 2·n on each of log₂ 256 = 8
passes. It is stable: with equal keys the element from the left
half is taken (LESS(a[j], a[i]) is false on equality). But it needs a second array
of the same size — for 256 numbers that is another 512 bytes. With 2 KB of RAM that is a quarter
of all memory, and so on a small chip merge sort is taken only when
stability is mandatory and the data are few.
76б.6 Comparison on six inputs
Comparisons, n = 256 (the last column is the worst of the six):
| Sort | random | sorted | reversed | all equal | 4 values | pyramid | worst |
|---|---|---|---|---|---|---|---|
sort_insert |
17138 | 255 | 32640 | 255 | 13001 | 16384 | 32640 |
sort_shell |
2490 | 1309 | 1961 | 1309 | 1561 | 1761 | 2490 |
sort_quick |
2385 | 1444 | 1466 | 1354 | 1679 | 3767 | 3767 |
sort_merge |
1712 | 1024 | 1024 | 1024 | 1620 | 1150 | 1712 |
Element moves (a swap counts as three):
| Sort | random | sorted | reversed | all equal | 4 values | pyramid |
|---|---|---|---|---|---|---|
sort_insert |
16888 | 0 | 32640 | 0 | 12748 | 16129 |
sort_shell |
1304 | 0 | 864 | 0 | 331 | 550 |
sort_quick |
1554 | 0 | 390 | 1536 | 1446 | 1349 |
sort_merge |
4096 | 4096 | 4096 | 4096 | 4096 | 4096 |
Note "all equal" for quicksort: 1536 moves when the answer is already there. Hoare partitioning swaps elements equal to the pivot — that is the price for the split staying in halves on equal keys instead of degenerating.
On 1000 random elements: insertion — 254514 comparisons, Shell — 13003, quicksort — 11529, merge — 8716. For comparison, n·log₂ n at n = 1000 is about 9966 (76.1): the last three are of the order of n log n, insertion is 25 times more.
Code and stack for Cortex-M4F and Cortex-M0, -O2:
| Function | code bytes M4 | stack frame M4 | code bytes M0 | stack frame M0 |
|---|---|---|---|---|
sort_insert |
68 | 12 | 60 | 20 |
sort_shell |
120 | 48 | 144 | 48 |
sort_quick |
368 | 200 | 440 | 208 |
sort_merge |
272 | 80 | 288 | 64 |
76б.7 What to choose with 2 KB of RAM and a predictable-time requirement
| Condition | Choice | Why |
|---|---|---|
| up to 20–30 elements | insertion | the least code, no worse than others at small n |
| the array is nearly sorted (one element added) | insertion | n comparisons instead of n log n |
| hundreds of elements, 2 KB of RAM, the worst case matters | Shell | no buffer, no recursion, spread across inputs under a factor of two |
| thousands of elements, the average time matters | quicksort with its own stack and a depth limit | the fewest comparisons on random data |
| stability is needed and there is memory for a copy | bottom-up merge | even time on any input |
| stability is needed, no memory | insertion or sorting keys with indices | merge does not fit |
Often the best choice is not to sort at all: keep the data ordered on insertion (76г), count a histogram instead of sorting (76з) or find the k-th element by partial partitioning if only that one is needed.
76б.8 ADC median filter
The median of a window is the middle in value of the last N samples. Unlike the mean it does not notice single outliers: interference, pickup from a relay, a conversion error pass by, while a step in the signal keeps its edge.
Computing the median by sorting the window anew each time is wasteful. It is better to keep an ordered copy next to the ring buffer: the outgoing sample is removed from it, the new one is inserted in its place — this is the same insertion sort, but for one element.
uint16_t med5_push(med5_t *f, uint16_t x)
{
uint16_t old = f->ring[f->pos];
f->ring[f->pos] = x;
f->pos = (uint8_t)((f->pos + 1) % MED_N);
int k = 0;
while (f->sorted[k] != old) k++; /* убрать уходящий отсчёт */
for (; k < MED_N - 1; k++) f->sorted[k] = f->sorted[k + 1];
k = MED_N - 1; /* вставить новый на своё место */
while (k > 0 && f->sorted[k - 1] > x) {
f->sorted[k] = f->sorted[k - 1];
k--;
}
f->sorted[k] = x;
return f->sorted[MED_N / 2];
}
A run on 60 samples of a 12-bit ADC around 2000 with noise of ±3. In the first half there are two outliers to 4095 in a row and one dip to 0, in the second — three outliers in a row:
| Interference | median of 5: largest deviation | mean of 5: largest deviation |
|---|---|---|
| two outliers in a row and one dip | 3 | 838 |
| three outliers in a row | 2095 | 1257 |
The median of 5 removes up to two outliers in a row completely — the deviation equals the noise. Three outliers in a row are already the majority of the window, and the median honestly passes them as a "new level". The rule: the median window is more than twice the length of the longest interference. For five, seven and nine samples the median can be computed without branches at all — that is the subject of 76в.
On M4 the function is 144 bytes; on M0 one more call appears in it — the remainder of division by 5 on M0 is computed by a library function, the core has no division instruction of its own. A power-of-two window or a counter with reset removes it.
76б.9 Pitfalls
The sort "hung" on sorted data. The pivot is the first or the last element. Sorted input is the most common in real life: the data are already sorted by the previous call. Median of three and a depth limit.
The stack overflowed only at the customer's site. Recursive quicksort on the bench went to a depth of 17, and on sorted data to 255, at 40 bytes per level. Own stack, smaller part first.
There are more postponed pieces than cells in the stack. The smaller part was pushed and the larger one handled at once. The rule is the opposite: the smaller one at once, the larger one onto the stack; then 16 cells are enough for 65 536 elements.
After sorting, events with equal priority got mixed up. Shell and quicksort are unstable. If stability is needed — insertion, merge or a key with an added sequence number.
The median filter lets interference through. The interference is longer than half the window. A window more than twice the length of the interference.
The library qsort ate stack and time. It is recursive, calls the
comparison function through a pointer for every comparison and on a small
chip gives no worst-case guarantee. An own sort of 100–400 bytes
of code is usually better.
76б.10 Summary
- On 256 elements the worst of six inputs: insertion — 32640 comparisons, Shell — 2490, quicksort with median of three — 3767, merge — 1712.
- Insertion: 255 comparisons on sorted input and 32640 on reversed; 68 bytes of code — for short and nearly sorted arrays.
- Shell with Ciura's gaps — no buffer and no recursion, 120 bytes on M4; with 2 KB of RAM and an even-time requirement it is the first candidate.
- Naive quicksort on sorted input went to a depth of 255 — 10200 bytes of stack; the own version keeps no more than log₂ n postponed pieces.
- Merge needs a second array: for 256
int16_tnumbers another 512 bytes. - The median of 5 removed two outliers in a row (deviation 3 against 838 for the mean), but let three through.
Next: section 76в "Sorting networks: median of 3, 5 and 9 without branches and constant time on Cortex-M" — how to sort a fixed number of elements with one and the same sequence of comparisons.