scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | Submodules | README | LICENSE

bsearch.c (525B)


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