The standard C library function bsearch
wasn't giving me correct results, apparently. So I decided to implement a binary searching function in place of it. It functions correctly up till now, though I haven't tested it thoroughly.
void * bsearch2(const void * base, const void * elem, const size_t nmemb, const size_t size, int (*compar)(const void *, const void *))
{
/* Looks for elem in array. If found returns its address, else returns NULL
Using the Binary Searching Algorithm, Assuming array to be sorted. */
if (nmemb == 0) return NULL;
size_t length = nmemb;
int result;
void * check;
while (length > 0) {
length = (length == 1) ? 0 : (size_t) length / 2;
check = (void *)(base + (size * length));
/* negative: element is greater, positive: element is smaller, zero: element is equal */
result = compar(check, elem);
if (result == 0)
return check;
if (result < 0) /* the element is in the second half */
base = check;
}
return NULL;
}
Are there any drawbacks in this function that I might be overlooking ?
bsearch
, with the exception that you have inverted the order of parameters in the predicate function. The standard one usescomp(key,item)
, yours iscomp(item,key)
. \$\endgroup\$bsearch
source code and I couldn't find it in glibc on ftp.gnu.org .. \$\endgroup\$