sort_r(9)

πŸ“¦ version 7.3.1, in nixpkgs unstable

πŸ’… 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 or NULL. you can bring your own swapper, or just pass NULL and 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 of cmp_func(b, a).
  • Transitivity: if cmp_func(a, b) <= 0 and cmp_func(b, c) <= 0, then cmp_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