qsort & bsearch in C
qsort sorts any array with a caller-supplied comparator: qsort(base, n, size, cmp) where cmp(const void*, const void*) returns negative/zero/positive. The void* generality sorts structs, strings, and numbers through one function — at the cost of per-comparison call overhead and cast-heavy comparators.
bsearch binary-searches sorted arrays with the same comparator shape, returning a pointer or NULL. Both demand consistency (same ordering for sort and search) and correct element sizes — wrong sizeof arguments silently sort garbage.
Comparator contract
int cmp(const void *a, const void *b) casts to the real type and returns <0/0/>0 — the entire ordering lives here.
qsort sorts anything
qsort(arr, n, sizeof *arr, cmp); — base pointer, count, element size, comparator. No type knowledge built in.
bsearch needs sorted input
bsearch(&key, arr, n, sizeof *arr, cmp) returns a pointer to the match or NULL — unsorted input gives nonsense.
Sizes must be exact
Wrong element sizes misalign every access — sizeof *arr (not a guessed constant) keeps it right.
#include <stdio.h>#include <stdlib.h> int cmp(const void *a, const void *b) { return *(const int *)a - *(const int *)b;} int main(void) { int v[] = {3, 1, 2}; qsort(v, 3, sizeof *v, cmp); printf("%d%d%d\n", v[0], v[1], v[2]); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.