initial attempt, may need fixing
This commit is contained in:
parent
77c2abd247
commit
04aba16c12
1 changed files with 31 additions and 0 deletions
31
stdlib/bsearch.c
Normal file
31
stdlib/bsearch.c
Normal file
|
@ -0,0 +1,31 @@
|
|||
#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;
|
||||
}
|
Loading…
Reference in a new issue