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 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.

Table 1. cmp_func() Return Value
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.

Table 2. Possible bsearch() Function Arguments
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
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 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.