void*  bsearch ( const void * key, const void * base, size_t num, size_t width, int (*fncomparison)(const void *, const void * ) );

Binary search.
  Searches the given key in an array pointed by base and formed by num elements each of a size of width bytes, and returns the address of the first entry in the table that matches the serach key. The comparison is performed by function fncomparison that is called back one or more times during the search.
  Because this function performs a binary search the values of the items in the array should be in ascending sorted order before the call.


Pointer to the object that serves as key for the search.
Pointer to the base of the array where the search is performed.
Number of elements in the array pointed by base.
Width of each element in the array.
Function that compares two elements. This should be provided by the caller to this function and must follow or be casted to a declaration like:
int fncompare (const void * elem1, const void * elem2 );
The function should receive two parameters (elem1 and elem2) that are pointers to elements, and should return an int value with the result of comparing them:
return valuedescription
<0*elem1 < *elem2
0*elem1 == *elem2
>0*elem1 > elem2

Return Value.
  A pointer to an entry in the array that matches the search key.
  If key is not found, a NULL pointer is returned.

  Defined in ANSI-C.


/* bsearch example */
#include <stdio.h>
#include <stdlib.h>

int values[] = { 10, 20, 25, 40, 90, 100 };

int compare (const void * a, const void * b)
  return ( *(int*)a - *(int*)b );

main ()
  int * pItem;
  int key = 40;
  pItem = (int*) bsearch (&key, values, 6, sizeof (int), compare);
  if (pItem!=NULL)
    printf ("%d is in the array",*pItem);
    printf ("%d is not in the array",key);
  return 0;
In the example there is an array of sorted int values. There is also a function called compare that compares the values pointed by the two parameters as if they were pointers to int values (that indeed they are) and returns the result of the subtraction, giving 0 if they are equal, greater than 0 if a points to a greater int than b or less than 0 if b points to a greater int than a.
In the main function there is a call to bsearch with 40 as key, so the function will find that key in the values array and the program will print out:
40 is in the array

See also.
  lsearch, qsort

© The C++ Resources Network, 2000