2020-12-02 05:38:11 +00:00
|
|
|
/*
|
|
|
|
* 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.
|
|
|
|
*/
|
|
|
|
|
2020-12-02 05:37:18 +00:00
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
|
|
void * bsearch(const void * key, const void * base, size_t nel, size_t width,
|
|
|
|
int (*compar)(const void *, const void*)) {
|
|
|
|
void * left;
|
|
|
|
void * right;
|
|
|
|
void * mid;
|
|
|
|
|
|
|
|
if(nel == 0 || base == NULL) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
left = base;
|
|
|
|
right = base + (nel * width);
|
|
|
|
|
|
|
|
while(left <= right) {
|
|
|
|
mid = (left + right) / 2;
|
|
|
|
int t = compar(key, mid);
|
|
|
|
if(t == 0) {
|
|
|
|
return mid;
|
|
|
|
}
|
|
|
|
else if(t < 0) {
|
|
|
|
right = mid - width;
|
|
|
|
}
|
|
|
|
else if(t > 0) {
|
|
|
|
left = mid + width;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return NULL;
|
|
|
|
}
|