Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

bsearch - conduct binary search of sorted array

&pagelevel(4)&pagelevel

Syntax

#include <stdlib.h>

void *bsearch(const void *key, const void *base, size_t nel,

size_t width, int ( *compar) (const void *, const void *));

Description bsearch() is a binary search function. It searches nel elements of an array base for the


value in the data item key. The size of each element in the array is specified by width.

compar() is a user-supplied comparison function which is called by bsearch() with two
arguments, a pointer to key and a pointer to an array element

compar() must return an integer less than, equal to, or greater than 0, depending on whether
the first argument is less than, equal to or greater than the second argument. The array
must consist of the following objects in the order given: all the elements that compare less
than, all the elements that compare equal to, and all the elements that compare greater than
the key object, in that order.

Return val.

Pointer to the sought element


if successful. If more than one instance of the element is found, there is no
indication as to which element the pointer refers to.

Null pointer

if no element has been found.

Notes

The pointers to the key and the element at the base of the array should be of type
pointer-to-element.

The comparison function need not compare every byte, so arbitrary data may be contained
in the elements in addition to the values being compared.

In practice, the elements of the array are usually sorted according to the comparison
function.

If the number of elements in the array is less than the size reserved for the array, nel should
be the lower number.

BS2000
If, for example, the qsort() function is used for sorting the array, it makes sense to use the
same comparison function compar() that is used by bsearch(). The current arguments of
qsort() are then pointers to two array elements to be compared. (End)

See also

hsearch(), lsearch(), qsort(), tsearch(), stdlib.h.