SDL_qsort(3)

πŸ’– SDL_qsort(3) β€” the SDL3 function that sorts your array, bestie πŸ’–

okay so like. you have an array. it's a mess. it's giving "unsorted chaos" energy. and you're like "someone please put this in order 😭". that someone is SDL_qsort, and she's from the SDL3 FUNCTIONS family, and she eats every single time. no cap.


✨ SYNOPSIS ✨

#include <SDL3/SDL_stdinc.h>

void SDL_qsort(void *base, size_t nmemb, size_t size, SDL_CompareCallback compare);

like, that's the whole vibe. four arguments. in, sorted, out. slay. πŸ’…


🌸 DESCRIPTION 🌸

SDL_qsort sorts an array. that's it. that's the post. it's an array sorter and it does the thing.

but fr fr, you gotta tell it how to sort, because it's not gonna guess what "in order" means for your little structs. so you hand it a compare callback and it does the rest. for example:

typedef struct {
    int key;
    const char *string;
} data;

int SDLCALL compare(const void *a, const void *b)
{
    const data *A = (const data *)a;
    const data *B = (const data *)b;

    if (A->n < B->n) {
        return -1;
    } else if (B->n < A->n) {
        return 1;
    } else {
        return 0;
    }
}

data values[] = {
    { 3, "third" }, { 1, "first" }, { 2, "second" }
};

SDL_qsort(values, SDL_arraysize(values), sizeof(values[0]), compare);

look at that. values walks in looking like a group chat with no pinned messages and walks out alphabetized, sorted, main character energy. πŸ‘‘

the way that compare callback works: return -1 if the first element goes before the second, 1 if it goes after, 0 if they're like, equal, whatever. that's the whole contract, bestie.

πŸŽ€ FUNCTION PARAMETERS πŸŽ€

  • base β€” a pointer to the start of the array. like, where the party begins. 🫢
  • nmemb β€” the number of elements in the array. yes babe, you have to count them, she's not psychic.
  • size β€” the size of the elements in the array. one element's size, not the whole thing. iykyk.
  • compare β€” a function used to compare elements in the array. your custom little vibe-checker. ✨

πŸ¦‹ THREAD SAFETY πŸ¦‹

it is safe to call this function from any thread. any thread. any time. she's unbothered, moisturized, in her lane, and thread-safe. periodt. πŸ’œ


🌈 AVAILABILITY 🌈

this function is available since SDL 3.2.0. so if you're on something older... no she's not there. upgrade bestie.


πŸ‘‘ SEE ALSO πŸ‘‘

  • SDL_bsearch(3) β€” for when you need to find a thing instead of sorting things. the search to her sort, fr fr.
  • SDL_qsort_r(3) β€” the version that lets you pass extra context through. her reentrant cousin who also ate. πŸ”₯

okay that's the whole page, you're sorted, go be iconic πŸ’–βœ¨πŸŽ€πŸ¦‹πŸŒΈπŸ’…πŸ«Ά

this has been SDL_qsort(3) from Simple Directmedia Layer, SDL 3.4.18 β€” written down for you with love, mwah, bye bestie πŸ’œπŸŒŸπŸ“

πŸ“¦ where this page comes from