FENIX_libc/stdlib/bsearch.c

42 lines
966 B
C
Raw Normal View History

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