C Library Function - bsearch()
C Standard Library - <stdlib.h>
Description
The C library function void bsearch(const void *key, const void *base, size_t nitems, size_t size, int (compar)(const void *, const void *)) performs a binary search on an array of nitems objects, where base points to the array to be searched, key points to the element to be found, and size specifies the size of each element in the array.
The contents of the array should be sorted in ascending order according to the comparison function compar.
Declaration
Here is the declaration for the bsearch() function.
void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))
Parameters
key -- A pointer to the element to be found, cast to void*.
base -- A pointer to the first object of the array to be searched, cast to void*.
nitems -- The number of elements in the array pointed to by base.
size -- The size of each element in the array in bytes.
compar -- The function that compares two elements.
Return Value
The function returns a pointer to an element in the array that matches if the search is successful, otherwise it returns a null pointer.
Example
The following example demonstrates the use of the bsearch() function.
#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int values[] = { 5, 20, 29, 32, 63 };
int main ()
{
int *item;
int key = 32;
/* Use bsearch() to find value 32 in the array */
item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
if( item != NULL )
{
printf("Found item = %d\n", *item);
}
else
{
printf("Item = %d could not be found\n", *item);
}
return(0);
}
Let's compile and run the above program, which will produce the following result:
Found item = 32