In https://nullprogram.com/blog/2023/02/11/ you write: > qsort is fine, though quality varies. [...] Similar story for bsearch. I disagree! The big annoyance with these functions is that the callback function doesn't take a user-provided context parameter, so that you can't implement a sorting or searching criterion that varies over time. void qsort_as_it_should_be(void *array, size_t nmem, size_t size, int (*cmp)(void *a, void *b, void *ctx), void *ctx_to_pass_to_cmp); An example might be if you've precomputed some auxiliary data that doesn't fit in the main array, in order to use it as the sorting criterion, and then you'll throw it away again afterwards. Cheers, Simon -- for k in [pow(x,37,0x1a1298d262b49c895d47f) for x in [0x50deb914257022de7fff, 0x213558f2215127d5a2d1, 0x90c99e86d08b91218630, 0x109f3d0cfbf640c0beee7, 0xc83e01379a5fbec5fdd1, 0x19d3d70a8d567e388600e, 0x534e2f6e8a4a33155123]]: print("".join([chr(32+3*((k>>x)&1))for x in range(79)])) # <email@example.com>
> callback function doesn't take a user-provided context parameter You're completely right, Simon. I've written on that issue in the past: C Closures as a Library https://nullprogram.com/blog/2017/01/08/ But I had forgotten about it here. So perhaps I should rank it lower than "fine." Though note that I hadn't described it as "good" or "great"!
On Sun, Feb 12, 2023 at 03:42:35PM +0000, Simon Tatham wrote: > The big annoyance with these functions is that the callback function > doesn't take a user-provided context parameter There does exist qsort_s, but it's Annex K: https://en.cppreference.com/w/c/algorithm/qsort There also exists qsort_r, but it's a GNU extension (and FreeBSD's qsort_r signature is incompatible with GNU's). The good news is that qsort_r (the GNU version) is accepted into the posix draft: https://www.austingroupbugs.net/view.php?id=900 Looks like the FreeBSD guys are going to deal with it via symbol versioning. So perhaps it's not too long until it lands in the ISO C standard as well. - NRK