#include <stdlib.h>
void *bsearch(const void *key,
const void *array,
size_t n,
size_t size,
cmp_func cmp());
bsearch() performs a binary search in a sorted array. It calls the comparison function cmp() with two arguments: a pointer to the key element that is to be found and a pointer to an array element. Thus, the type cmp_func can be declared as:
typedef int (*cmp_func)(const void *key, const void *data);
The comparison function returns an integer according to, as listed in the following table:
| Key element value | Return value |
|---|---|
| less than the array element | less than zero (negative) |
| equal to the array element | zero |
| greater than the array element | greater than zero (positive) |
The arguments of bsearch() are as listed in the following table:
| Parameter Name | Meaning |
|---|---|
| key | A pointer to the key data you are seeking |
| array | A pointer to the beginning (i.e., the first element) of the array that is searched |
| n | The number of elements in the array |
| size | The size (in bytes) of one element in the table |
| cmp() | The comparison function |
bsearch() returns a pointer to an element of the array that matches the key, if there is one. If the comparison function never returns zero, i.e., there is no matching array element, bsearch() returns NULL.