qsort() Sort an array with a comparison function
qsort() Sort an array with a comparison function
qsort() sorts an array in place using a consistent, transitive comparator. Stability is not guaranteed; avoid comparator subtraction, which may overflow.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / C90 |
📝 Syntax
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
⚙️ Parameters
| base Required | A pointer to the first element of the array to sort. |
|---|---|
| nmemb Required | The number of elements in the array. |
| size Required | The size of each element in bytes. |
| compar Required | Compares two elements and returns negative, zero, or positive when the first is less than, equal to, or greater than the second. |
Returns: No value is returned.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
7 7 19 42 88
⚠️ Warning The comparator must define a consistent, transitive ordering. Avoid return *(int *)a - *(int *)b because the subtraction can overflow.
💡 Tip Use sizeof array[0] for size and the element count for nmemb. Inside the comparator, convert each pointer to the correct element type.
🏷️ Related stdlib.h functions
📚 Related Tutorials
❓ FAQ
QWhy shouldn't a qsort comparator simply subtract the two integers?
ASubtracting extreme values can overflow signed int, causing undefined behavior and invalid ordering. Compare the values and return -1, 0, or 1 instead.
QIs qsort a stable sort?
AThe C standard does not guarantee stability, so equivalent elements need not retain their original order. Include an original index in the ordering or implement stability yourself if needed.
QWhy does a qsort comparator receive char ** when sorting an array of strings?
Aqsort passes the comparator a pointer to an array element. If each element is a char *, the element address is a char **. The comparator should convert it to const char *const *, dereference it to obtain the string pointer, and pass that pointer to strcmp; it must not treat the element address itself as the start of a string.