This commit was generated by cvs2svn to compensate for changes in r2,
which included commits to RCS files with non-trunk default branches. git-svn-id: svn://svn.cc65.org/cc65/trunk@3 b7a2c559-68d2-44c3-8de9-860c34a00d81
This commit is contained in:
48
libsrc/common/bsearch.c
Normal file
48
libsrc/common/bsearch.c
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* bsearch.c
|
||||
*
|
||||
* Ullrich von Bassewitz, 17.06.1998
|
||||
*/
|
||||
|
||||
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
|
||||
|
||||
void* bsearch (void* key, void* base, size_t n, size_t size, int (*cmp) (void*, void*))
|
||||
{
|
||||
int current;
|
||||
int result;
|
||||
int found = 0;
|
||||
int first = 0;
|
||||
int last = n - 1;
|
||||
|
||||
/* Binary search */
|
||||
while (first <= last) {
|
||||
|
||||
/* Set current to mid of range */
|
||||
current = (last + first) / 2;
|
||||
|
||||
/* Do a compare */
|
||||
result = cmp ((void*) (((int) base) + current*size), key);
|
||||
if (result < 0) {
|
||||
first = current + 1;
|
||||
} else {
|
||||
last = current - 1;
|
||||
if (result == 0) {
|
||||
/* Found one entry that matches the search key. However there may be
|
||||
* more than one entry with the same key value and ANSI guarantees
|
||||
* that we return the first of a row of items with the same key.
|
||||
*/
|
||||
found = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Did we find the entry? */
|
||||
return (void*) (found? ((int) base) + first*size : 0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user