bsearch
void* bsearch ( const void * key, const void * base, size_t num, size_t width, int (*fncomparison)(const void *, const void * ) ); | stdlib.h |
cplusplus.com |
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.
Parameters.
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 value description <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.
Portability.
Defined in ANSI-C.
Example.
/* 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);
else
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