bsearch()

Syntax
  #include <stdlib.h> 
  void *bsearch(const void *key, 
                const void *array,
                size_t n, 
                size_t size,
                cmp_func cmp());  
Description

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:

Table 1. Return value from the comparison function, cmp_func()
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:

Table 2. Possible arguments to the bsearch() function
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
Note: Make sure the array contains only elements of the same size. bsearch() also assumes that the array is sorted in ascending order with respect to the comparison function cmp().
Return

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.