C Programming • C17 baseline, standards-specific features labeled
Sorting and Searching with qsort and bsearch
Use standard-library algorithms with comparators that obey a consistent ordering.
qsort orders an array using a comparator callback; bsearch uses the same ordering rule to locate a key. The comparator must not subtract values when that subtraction could overflow. Search only after sorting with a compatible comparator.
Example
#include <stdlib.h>
static int compare_ints(const void *left, const void *right) {
int a = *(const int *)left;
int b = *(const int *)right;
return (a > b) - (a < b);
}
int main(void) {
int values[] = {9, 2, 6, 4};
int key = 6;
qsort(values, 4, sizeof values[0], compare_ints);
int *found = bsearch(&key, values, 4, sizeof values[0], compare_ints);
return found == NULL;
}
What to expect
The array is sorted, and bsearch returns a pointer to the matching value 6.
Key idea: The comparator defines the ordering contract; the array passed to bsearch must already follow that exact order.