Go to the previous, next section.

Array Search Function

To search a sorted array for an element matching the key, use the bsearch function. The prototype for this function is in the header file `stdlib.h'.

Function: void * bsearch (const void *key, const void *array, size_t count, size_t size, comparison_fn_t compare)

The bsearch function searches the sorted array array for an object that is equivalent to key. The array contains count elements, each of which is of size size bytes.

The compare function is used to perform the comparison. This function is called with two pointer arguments and should return an integer less than, equal to, or greater than zero corresponding to whether its first argument is considered less than, equal to, or greater than its second argument. The elements of the array must already be sorted in ascending order according to this comparison function.

The return value is a pointer to the matching array element, or a null pointer if no match is found. If the array contains more than one element that matches, the one that is returned is unspecified.

This function derives its name from the fact that it is implemented using the binary search algorithm.

Go to the previous, next section.