man c/qsort
qsort is not always quicksort: what C libraries really do
You call qsort and expect quicksort. The name suggests it. The C standard never says so, and two of the four libraries below run something else.
This article covers glibc 2.42, musl 1.2.5, FreeBSD 15.0 and Apple’s Libc at tag Libc-1752.120.2, the newest one Apple has published. Facts come from source at those tags, commit messages and release notes. Experiments ran on macOS 27.2.1 (Apple M2 Pro, Apple clang 21). I could only run the macOS library, so everything about glibc, musl and FreeBSD comes from reading their source. I can’t prove which Libc tag macOS 27.2.1 was built from, so the macOS numbers describe the installed library.
What the standard promises
C11 (N1570 7.22.5.2) and C23 (N3220 7.24.5.2) say qsort sorts the array “into ascending order according to a comparison function”. The next sentence covers ties. “If two elements compare as equal, their order in the resulting sorted array is unspecified.”
There is no complexity bound and no algorithm. Equal elements may come out in any order. The surrounding clause (N3220 7.24.5) adds rules for you. Your comparator must define a total order and must not modify the array. Both of its arguments point into the array. The library may move elements between calls. POSIX defers to ISO C for qsort.
The short version
| Library | Algorithm | Stable | Worst case | Extra memory |
|---|---|---|---|---|
| glibc 2.42 | merge sort, heapsort if malloc fails | merge path yes | O(n log n) | stack up to 1024 bytes, else malloc |
| musl 1.2.5 | smoothsort | no promise | O(n log n) | O(1) |
| FreeBSD 15.0 | Bentley-McIlroy quicksort | no | O(n²) | none, recursion |
| macOS | Bentley-McIlroy quicksort, depth limit, heapsort | no | O(n log n) | heapsort fallback mallocs one element |
glibc: a merge sort since version 1.04
glibc’s NEWS for version 1.04 says Mike Haertel wrote a merge sort that “is said to be significantly faster” than the old GNU sort. It became the standard qsort, and the old function ran “when the required storage is not available”.
In 2.42, __qsort_r returns at once for fewer than two elements. It needs a buffer of n * size bytes. Elements larger than 32 bytes are sorted indirectly. It sorts an array of pointers, then moves each element once into place. If the buffer fits in 1024 bytes, it lives on the stack. Otherwise glibc calls malloc, and if that fails it runs an in-place heapsort. So 256 ints sort on the stack and 257 ints call malloc.
The merge takes from the left run when the comparator returns <= 0, which makes it stable. The heapsort fallback is not.
glibc almost dropped all of this. In October 2023 two commits replaced the merge sort with introsort. Their motivation listed the malloc latency, async-signal safety and slow handling of sorted input. On 15 January 2024, before glibc 2.39 was tagged, Adhemerval Zanella reinstated the merge sort. The commit message says stability “has become an instance of Hyrum’s law where multiple programs expect it”, and that the introsort “is not faster than the previous mergesort”. The 2.39 tag has the merge sort. No release shipped the introsort.
The revert also changed the fallback. Up to 2.38, msort.c refused to malloc more than a quarter of physical memory, measured with sysconf(_SC_PHYS_PAGES). It also used alloca for small buffers, and it fell back to an older quicksort. From 2.39 on there is a fixed stack buffer and a heapsort fallback. In 2.42 the buffer is also freed when a C++ comparator throws (bug 32058).
musl: smoothsort, no allocation
musl’s qsort.c opens with “Smoothsort, an adaptive variant of Heapsort. Memory usage: O(1). Run time: Worst case O(n log n), close to O(n) in the mostly-sorted case.” The code is Valentin Ochs’s from 2011. Its extra storage is a few fixed-size stack arrays, one of them a table of Leonardo numbers. musl’s release notes list smoothsort as new in 0.7.10.
Plain qsort is a wrapper in qsort_nr.c. It calls __qsort_r with a small function that forwards to your comparator. The source makes no stability promise, so treat it as unstable.
FreeBSD: Bentley-McIlroy as published
FreeBSD’s qsort.c says it is the “Qsort routine from Bentley & McIlroy’s ‘Engineering a Sort Function’”, the 1993 paper. It uses insertion sort below 7 elements and a median of three. Above 40 elements it takes the median of three medians, which the paper calls Tukey’s “ninther”. Partitioning moves elements equal to the pivot to both ends, then swaps them into the middle. It recurses on the smaller side and loops on the larger. The man page says it “does not allocate memory, it is implemented using recursion”.
Nothing bounds the recursion depth. McIlroy’s 1999 paper “A Killer Adversary for Quicksort” builds bad input on the fly from the comparisons a quicksort makes. It drove Bentley’s qsort to about 0.088n² comparisons.
Until 2025 the BSD code had one more branch. If a partition pass made no swaps, it switched to insertion sort for the whole range. A commit on 15 August 2025 removed it. Its message says “the switch to insertion sort in the BSD qsort code is based on a misunderstanding of Knuth’s TAOCP and is actually a pessimization.” Its test says that with the old branch, a simple pattern needs “roughly N * N / 4 comparisons”. The branch is in release/14.0.0 and gone in release/15.0.0. Ray Gardner’s write-up traces it to 4.4BSD-Lite, and reports that NetBSD removed it in 2009 and OpenBSD in 2014.
macOS: the FreeBSD code with guard rails
Apple keeps FreeBSD’s file at stdlib/FreeBSD/qsort.c. It differs from FreeBSD 15.0 in three ways:
- A depth limit of
2 * (flsl(n) - 1), about 2 log2 n. When it runs out, the range goes toheapsort. - The no-swaps branch stays, but insertion sort gives up after
1 + n / 4swaps and returns to quicksort. - Swaps move a
longorintat a time when alignment allows. FreeBSD dropped that in 2018 because the aliasing broke under link-time optimization.
The depth limit is present by Libc-825.40.1 and absent at Libc-763.13.
I counted comparator calls on 2^20 ints with the installed qsort:
| Input | Comparisons | ÷ n log2 n |
|---|---|---|
| sorted | 2,097,159 | 0.10 |
| reversed | 10,485,923 | 0.50 |
| random | 21,822,321 | 1.04 |
| organ pipe | 21,601,573 | 1.03 |
| all equal | 1,048,587 | 0.05 |
| random 0s and 1s | 1,572,154 | 0.08 |
| FreeBSD’s pathological test pattern | 9,305,788 | 0.44 |
| McIlroy’s adversary | 62,704,828 | 2.99 |
The adversary ratio stayed at 2.97 to 2.99 at n = 2^14, 2^16, 2^18 and 2^20, so it does not grow like n². I interposed malloc to see why. Sorting a scrambled permutation of 2^16 ints called it 0 times. The adversary run on 2^16 called it twice, 4 bytes each, which is the heapsort fallback asking for one int.
That contradicts Apple’s man page, which says “qsort does not allocate memory”. heapsort returns -1 before sorting if that malloc fails, and _qsort ignores the return value. That range would stay unsorted.
Stability is easy to break. I sorted structs by a key and counted adjacent equal-key pairs that came out of input order. Seven records with 2 keys gave 0, because that is pure insertion sort. Eight records gave 3. A million records with 16 keys gave 469,246.
qsort_r: one name, two signatures
A comparator often needs context, such as a sort column. qsort_r passes one pointer through. The libraries disagree on where it goes.
| Who | Call | Comparator |
|---|---|---|
| POSIX.1-2024, glibc, musl, FreeBSD 14.0+ | qsort_r(base, n, size, cmp, arg) | cmp(a, b, arg) |
| macOS, FreeBSD before 14.0 | qsort_r(base, n, size, thunk, cmp) | cmp(thunk, a, b) |
glibc exports qsort_r under symbol version GLIBC_2.8, and 2.42 declares it only with _GNU_SOURCE. musl added it in 1.2.3. POSIX added it in Issue 8 (Austin Group Defect 900) with the glibc order. FreeBSD’s 2022 commit that switched to that order says glibc introduced “their own qsort_r(3) interface in 2007” despite knowing FreeBSD’s. FreeBSD keeps old binaries working with a FBSD_1.0 compatibility symbol, and old source with C11 _Generic.
On macOS a GNU-order call is not a compile error. Apple clang 21 with -std=c11 only warns with -Wincompatible-pointer-types. The program then calls the context pointer as a function and dies with exit status 139 (SIGSEGV).
qsort_s and Annex K
C11 Annex K (N1570 K.3.6.3.2, N3220 K.3.6.3.3) defines:
errno_t qsort_s(void *base, rsize_t nmemb, rsize_t size,
int (*compar)(const void *x, const void *y, void *context),
void *context);
The comparator takes context last, like POSIX qsort_r. qsort_s checks that nmemb and size are at most RSIZE_MAX and that the pointers are not null when nmemb is nonzero. On a violation it does not sort and returns nonzero. Equal elements still land in unspecified order. Annex K is optional. An implementation announces it by defining __STDC_LIB_EXT1__ (N3220 6.10.10.4).
Of the four, only FreeBSD ships qsort_s, added in January 2020. glibc 2.42 and musl 1.2.5 do not declare it. On macOS, a call with __STDC_WANT_LIB_EXT1__ defined fails with “call to undeclared function ‘qsort_s’”, and libsystem_c.dylib exports no such symbol.
Curious facts
- glibc 2.42’s
qsort.cstill opens with “If you consider tuning this algorithm, you should consult first: Engineering a sort function”. It contains a merge sort and a heapsort. - The old glibc quicksort stopped partitioning below 4 elements. The comment says the number “was chosen to work best on a Sun 4/260”.
- Apple’s
heapsort.ccomment says the BSD quicksort’s median selection makes the chance of hitting its worst case “nonexistent”. McIlroy’s adversary was published in 1999. - Bentley and McIlroy began after a colleague’s sort needed n² comparisons on an “organ-pipe” array. Their paper says “The sort need not be stable”.
History
- 1983: a Berkeley qsort that the 1993 paper found quadratic on random zeros and ones.
- glibc 1.04: Haertel’s merge sort becomes
qsort. - 1993: Bentley and McIlroy, “Engineering a Sort Function”, SP&E 23(11).
- 1999: McIlroy, “A Killer Adversary for Quicksort”.
- musl 0.7.10: smoothsort. musl 1.2.3:
qsort_r. - By Libc-825.40.1: Apple has the depth limit and heapsort fallback.
- January 2020: FreeBSD adds
qsort_s. - 2022, FreeBSD 14.0:
qsort_rtakes the GNU order. - October 2023 to January 2024: glibc tries introsort and reverts before 2.39.
- 2024: POSIX.1-2024 adds
qsort_r. - 2025, glibc 2.42: buffer freed on C++ exceptions.
- August 2025, FreeBSD 15.0: the no-swaps insertion-sort branch is removed.
Sources
- glibc 2.42
stdlib/qsort.c: Bentley-McIlroy comment,heapsort_r, buffer limits, stable merge,qsort_r_malloc,__qsort_r - glibc 2.38:
msort.c__qsort_r,qsort.cMAX_THRESH; 2.39qsort.c - glibc commits: introsort, remove mergesort, reinstate mergesort, exception leak fix
- glibc 2.42: NEWS (1.04 merge sort; bug 32058 at line 115),
stdlib/Versions,stdlib.h - musl 1.2.5:
qsort.c,qsort_nr.c, WHATSNEW (and 1.2.3) - FreeBSD 15.0:
qsort.c,qsort_r_compat.c,qsort.3; 14.0qsort.c - FreeBSD commits: drop insertion-sort switch,
qsort_rprototype,qsort_s, stop aliasing - Apple Libc-1752.120.2:
qsort.c,heapsort.c,qsort.3; older: Libc-825.40.1, Libc-763.13 - Standards: N1570 7.22.5.2 and K.3.6.3.2; N3220 7.24.5, 6.10.10.4 and K.3.6.3.3; POSIX.1-2024
qsort - Papers: Bentley and McIlroy, 1993; McIlroy, 1999; Ray Gardner, “Re-engineering a qsort, part 3”
grep -rl /lib/c/qsort/
ls c/
- draft Why C programmers write their own hash tablesThe C library has no map, POSIX hsearch gives you one global string table that behaves differently on every libc, and a usable open-addressing table fits in about a hundred lines.