bsearch() Perform Binary Search
#include <search.h>
char *bsearch(key,base,num,width,compare);
char *key; Search key
char *base; Pointer to base of search data
unsigned num, width; Number and width of elements
int (*compare)(); Pointer to compare function
bsearch() is designed to search a table of information. The table is
a sorted array of 'num' elements, each of size 'width' bytes. 'base'
is a pointer to the base of the array being searched. 'key' is the
item being sought. 'compare' points to a user-supplied routine that
compares two array elements and returns a value based on the
comparison.
bsearch() calls the compare() function one or more times during the
search, each time passing pointers to two array elements. Compare()
should compare the two elements and return one of the following
values:
< 0 element1 is less than element2
0 element1 is identical to element2
> 0 element1 is greater than element2
Returns: A pointer to the first occurrence of 'key' in the array
pointed to by 'base'. NULL is returned if 'key' is not
found.
Notes: The elements of the array pointed to by 'base' should
already be in ascending order before being searched.
-------------------------------- Example ---------------------------------
The following statements search an array for a value and print out an
appropriate message.
#include <search.h>
#include <stdio.h>
#include <string.h>
int vals[] = {10,20,30,40,50,60,70,80,90,100};
int num = 10;
int key = 60;
int *found;
int cmp();
main()
{
found = (int *)bsearch(&key,vals,num,sizeof(int),cmp);
if (found == 0)
printf("%d already in table\n",key);
else
printf("%d not found\n",key);
}
int cmp(n1,n2)
int *n1;
int *n2;
{
return(*n1 - *n2);
}
Seealso:
This page last updated on Fri Nov 30 10:48:32 MSK 2001
Copyright © 1992-2001, Vitaly Filatov, Moscow, Russia
Webmaster