#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 cmp_func type can be declared as:
typedef int (*cmp_func)(const void *key,
const void *data);
The comparison function returns an integer according to the following table.
| Key Element | Expected 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 following table lists the arguments of bsearch() are.
| Parameter Name | Meaning |
|---|---|
| key | A pointer to the key data you are seeking |
| array | A pointer to the beginning (that is, 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 array element that matches the key, if one exists. If the comparison function never returns zero (that is, no matching array element exists), bsearch() returns NULL.