qsort
qsort is the C standard library's generic sort. It sorts an array in place using a comparison function you supply. The name hints at quicksort; the standard does not require that algorithm.
Detailed Explanation
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
base is the first element. nmemb is how many. size is sizeof one element. compar returns negative, zero, or positive the way strcmp does. The library moves bytes of size around; it does not know your type. Inside compar you cast the const void * back to const T * and compare the fields you care about.
compar must define a consistent order. If it disagrees with itself — a < b and b < a both true, or a changing field — the sort may crash, loop, or produce garbage. It must not modify the elements in a way that changes later comparisons. It must not assume the pointers have any alignment other than the element's.
qsort is not stable. Equal elements may swap order. If you need stability, sort an array of indices with a comparator that breaks ties on the index, or use a stable algorithm.
The function does not report errors. A NULL base with nmemb > 0 is undefined. nmemb == 0 is a no-op. The comparator is called a large number of times; keep it cheap. For int, a subtract can overflow; compare with < and return -1, 0, or 1.
C11 added qsort_s with a context pointer; it is optional and poorly portable. The usual way to pass context is a file-scope variable (not thread-safe) or to sort an array of structs that already contain everything the comparator needs. POSIX qsort_r / BSD qsort_r pass a thunk, with argument orders that disagree with each other. Prefer putting the key in the element.
Code Examples
#include <stdio.h>
#include <stdlib.h>
static int cmp_int(const void *a, const void *b)
{
int x = *(const int *)a;
int y = *(const int *)b;
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
}
int main(void)
{
int a[] = { 3, 1, 4, 1, 5 };
qsort(a, 5, sizeof a[0], cmp_int);
printf("%d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4]);
/* prints: 1 1 3 4 5 */
return 0;
}#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int cmp_str(const void *a, const void *b)
{
const char *const *ps = a;
const char *const *pt = b;
return strcmp(*ps, *pt);
}
int main(void)
{
const char *names[] = { "c", "go", "c" };
qsort(names, 3, sizeof names[0], cmp_str);
printf("%s %s %s\n", names[0], names[1], names[2]);
/* prints: c c go */
return 0;
}Common Gotchas
`qsort` is not stable and not guaranteed to be quicksort
do not depend on equal-key order or on `O(n log n)` worst-case unless your libc documents it.