BSEARCH(3C) DOMAIN/IX SYS5 BSEARCH(3C)
NAME
bsearch - binary search a sorted table
USAGE
#include <search.h>
char *bsearch((char *) key, (char *) base, nel, sizeof(*key), compar)
unsigned nel;
int (*compar)();
DESCRIPTION
Bsearch is a binary search routine generalized from Knuth
(6.2.1) Algorithm B. It returns a pointer into a table
indicating where a datum may be found. The table must have
been sorted previously, in increasing order according to a
comparison function that you have provided. Key points to
the datum to be sought in the table. Base points to the
element at the base of the table. Nel is the number of ele-
ments in the table. Compar is the name of the comparison
function, which is called with two arguments that point to
the elements being compared. The comparison function must
return an integer less than, equal to, or greater than zero
according to whether the first argument is to be considered
less than, equal to, or greater than the second.
NOTES
The pointers to the key and the element at the base of the
table should be of type pointer-to-element, and cast to type
pointer-to-character.
The comparison function need not compare every byte, so
arbitrary data can be contained in the elements, along with
the values being compared.
Although declared as type pointer-to-character, the value
returned should be cast into type pointer-to-element.
EXAMPLE
The example below searches a table that contains pointers to
items consisting of a string and its length. The table is
ordered alphabetically on the string in the item pointed to
by each entry.
This code fragment reads in strings and either finds the
corresponding item and prints out the string and its length,
or prints an error message.
#include <stdio.h>
#include <search.h>
Printed 12/4/86 BSEARCH-1
BSEARCH(3C) DOMAIN/IX SYS5 BSEARCH(3C)
#define TABSIZE 1000
struct item { /* these are stored in the table */
char *string;
int length;
};
struct item table[TABSIZE]; /* table to be searched */
.
.
.
{
struct item *item_ptr, item;
int item_compare( ); /* routine to compare 2 items */
char str_space[20]; /* space to read string into */
.
.
.
item.string = str_space;
while (scanf("%s", item.string) != EOF) {
item_ptr = (struct item *)bsearch((char *)(&item),
(char *)table, TABSIZE,
sizeof(struct item), item_compare);
if (item_ptr != NULL) {
(void)printf("string = %20s, length = %d\n",
item_ptr->string, item_ptr->length);
} else {
(void)printf("not found: %s\n", item.string);
}
}
}
/*
This routine compares two items based on an
alphabetical ordering of the string field.
*/
int
item_compare(item1, item2)
struct item *item1, *item2;
{
return strcmp(item1->string, item2->string);
}
DIAGNOSTICS
A NULL pointer is returned if the key cannot be found in the
table.
RELATED INFORMATION
hsearch(3C), lsearch(3C), qsort(3C), tsearch(3C)
BSEARCH-2 Printed 12/4/86