Learn C
#include "stdlib/qsort_bsearch.h"

qsort & bsearch in C

#concept

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.

#how it works
1

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.

2

qsort sorts anything

qsort(arr, n, sizeof *arr, cmp); — base pointer, count, element size, comparator. No type knowledge built in.

3

bsearch needs sorted input

bsearch(&key, arr, n, sizeof *arr, cmp) returns a pointer to the match or NULL — unsorted input gives nonsense.

4

Sizes must be exact

Wrong element sizes misalign every access — sizeof *arr (not a guessed constant) keeps it right.

#example
#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;
}
Output
123
1The comparator casts void* back to int* and subtracts — negative/zero/positive ordering in one line.
2qsort rearranges through the comparator without knowing the element type itself.
3123 prints — sorted ascending through a fully generic interface.
#use cases
Sorting any array type with one comparator per ordering
Binary searching sorted tables with bsearch + NULL checks
Struct sorting by comparing key fields inside comparators
Sizing elements with sizeof *arr, never magic numbers

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.