home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Amiga Format 61
/
af061sub.adf
/
SmileyV3.lha
/
sources
/
bsearch.c
next >
Wrap
C/C++ Source or Header
|
1994-05-13
|
897b
|
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 */
}