sort_r(9)
π sort_r(9) β the kernel's very own sort bestie π
okay so this is a page straight out of the Kernel API Manual, and it's about sort_r β the function that puts your array in order. yes, that kind of order. let's get into it β¨
β¨ SYNOPSIS β¨
void sort_r (void *base , size_t num , size_t size , cmp_r_func_t
cmp_func , swap_r_func_t swap_func , const void *priv );
like, one function, six arguments, zero chill. π«Ά
πΈ ARGUMENTS πΈ
baseβ pointer to data to sort. this is your lil pile of stuff, the main character of the whole operation πnumβ number of elements. how many things are in the pile, bestie.sizeβ size of each element. every element's personal space πcmp_funcβ pointer to comparison function. the vibe checker that decides who goes first.swap_funcβ pointer to swap function orNULL. you can bring your own swapper, or just passNULLand let the built-in one handle it πprivβ third argument passed to comparison function. your little secret handoff, iykyk π
π¦ DESCRIPTION π¦
so like, this function does a heapsort on the given array. not quicksort, not a vibes-based shuffle β heapsort, periodt.
you may provide a swap_func function if you need to do something more than a memory copy (e.g. fix up pointers or auxiliary data), but the built-in swap avoids a slow retpoline and so is significantly faster. so like... only bring your own if you actually need to, ngl. the default one ate. π₯
the comparison function must adhere to specific mathematical properties to ensure correct and stable sorting:
- Antisymmetry:
cmp_func(a, b)must return the opposite sign ofcmp_func(b, a). - Transitivity: if
cmp_func(a, b) <= 0andcmp_func(b, c) <= 0, thencmp_func(a, c) <= 0.
girl. do NOT skip these. your comparison function has to be mathematically well-behaved or the sort just gives you nonsense. no cap. π
sorting time is O(n log n) both on average and worst-case. while quicksort is slightly faster on average, it suffers from exploitable O(n*n) worst-case behavior and extra memory requirements that make it less suitable for kernel use. so yeah β heapsort is the safe, reliable, main character energy choice here, and quicksort is out here getting exploited π
β SEE ALSO β
kernel file ./lib/sort.c is_aligned(9), swap_words_32(9), swap_words_64(9), swap_bytes(9), parent(9), sort_r_nonatomic(9)
like, go read the source if you want the full lore π§
and that's the whole page, bestie β brought to you by the fine folks over at ./lib, dated October 2026. slay. π
π¦ where this page comes from
- nixpkgs unstable: linux-manual 7.3.1
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms