42 lines
No EOL
966 B
C
42 lines
No EOL
966 B
C
/*
|
|
* bsearch - binary search!
|
|
*
|
|
* This header is a part of the FENIX C Library and is free software.
|
|
* You can redistribute and/or modify it subject to the terms of the
|
|
* Clumsy Wolf Public License v4. For more details, see the file COPYING.
|
|
*
|
|
* The FENIX C Library is distributed WITH NO WARRANTY WHATSOEVER. See
|
|
* The CWPL for more details.
|
|
*/
|
|
|
|
#include <stdlib.h>
|
|
|
|
void * bsearch(const void * key, const void * base, size_t nel, size_t width,
|
|
int (*compar)(const void *, const void*)) {
|
|
long int left;
|
|
long int right;
|
|
long int mid;
|
|
|
|
if(nel == 0 || base == NULL) {
|
|
return NULL;
|
|
}
|
|
|
|
left = (long int) base;
|
|
right = (long int) (base + (nel * width));
|
|
|
|
while(left <= right) {
|
|
mid = (left + right) / 2;
|
|
int t = compar(key, (void *) mid);
|
|
if(t == 0) {
|
|
return (void *) mid;
|
|
}
|
|
else if(t < 0) {
|
|
right = mid - width;
|
|
}
|
|
else if(t > 0) {
|
|
left = mid + width;
|
|
}
|
|
}
|
|
|
|
return NULL;
|
|
} |