home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The World of Computer Software
/
World_Of_Computer_Software-02-385-Vol-1of3.iso
/
s
/
smiley40.zip
/
BSEARCH.C
next >
Wrap
C/C++ Source or Header
|
1993-01-17
|
932b
|
36 lines
/*
* A binary search generalized from Knuth (6.2.1) Algorithm B just
* like the AT&T man page says...
*
* Written by reading the System V Interface Definition, not the code.
*
* Totally public domain.
*/
/*LINTLIBRARY*/
char *bsearch(key, base, nel, width, compar)
char *key; /* Key to be located */
char *base; /* Beginning of table */
unsigned nel; /* Number of elements in the table */
unsigned width; /* Width of an element (bytes) */
int (*compar)(); /* Comparison function */
{
int doublewidth = width + width;
char *last = base + width * (nel - 1);
while (last >= base)
{
register char *p = base + width * ((last - base)/doublewidth);
register int cmp = (*compar)(key, p);
if (cmp == 0)
return (p); /* aha, we found it! */
if (cmp < 0)
last = p - width;
else
base = p + width;
}
return ((char *) 0); /* didn't find it */
}