9os

Experimental kernel using plan9 ideas for embedded device
git clone git://git.simple-cc.org/9os
Log | Files | Refs | README | LICENSE

bsearch.c (439B)


      1 #include <stdlib.h>
      2 
      3 void *
      4 bsearch(const void *key, const void *ary, size_t n, size_t size,
      5         int (*cmp)(const void *, const void *))
      6 {
      7 	int t;
      8 	size_t mid, low, high;
      9 	char *cur, *base = ary;
     10 
     11 	low = 0;
     12 	high = n - 1;
     13 	while (low <= high) {
     14 		mid = low + (high - low) / 2;
     15 		cur = base + mid*size;
     16 
     17 		if ((t = (*cmp)(key, cur)) == 0)
     18 			return cur;
     19 		else if (t > 0)
     20 			low = mid + 1;
     21 		else
     22 			high = mid - 1;
     23 	}
     24 
     25 	return NULL;
     26 }