C bsearch
bsearch searches a sorted array and returns a pointer to a matching element. A null pointer indicates a miss.
A simple example
bsearch
- Start with Sorted values 1, 3, 5
- Do this Search for 3
- Result Found in the middle
Syntax
bsearch(&key, items, count, sizeof items[0], compare)
Run this example in C
Save the program as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
Look up an item in a sorted catalog
A price catalog is already sorted and can contain repeated thresholds. Locate the correct boundary and check what the returned position means when an exact value is absent.
#include <stdio.h>
#include <stdlib.h>
static int compare(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 catalog[] = {10, 20, 30, 40};
int queries[] = {30, 25};
for (size_t i = 0; i < 2; ++i) {
const int *item = bsearch(&queries[i], catalog, 4, sizeof catalog[0], compare);
printf("%s %d\n", item ? "found" : "missing", queries[i]);
}
return 0;
}
found 30 missing 25
The catalog must be sorted according to the same ordering used by the lookup. With duplicate keys, any matching element can be returned.
Open Group function reference for bsearch
Locate a numbered tote
A parcel clerk keeps tote numbers in ascending order. Find the specified item in the sorted register. How many smaller entries come before it?
Find the earliest permit
A permit clerk starts with the smallest valid identifier. Find the specified item in the sorted register. How many smaller entries come before it?