在移植glib到wince环境时,发现wince的c runtime library不包含很多库函数,诸如 bsearch() 半則搜索法,其用法有点像 std::bind2nd(),
费了点时间将其刨了出来,相信对有些人有用
1 void * bsearch(
2 const void *key,
3 const void *base0,
4 size_t nmemb,
5 size_t size,
6 int (*compar)(const void *, const void *)) {
7
8 const char *base = base0;
9 size_t lim;
10 int cmp;
11 const void *p;
12
13 for (lim = nmemb; lim != 0; lim >>= 1) {
14 p = base + (lim >> 1) * size;
15 cmp = (*compar)(key, p);
16 if (cmp == 0)
17 return ((void *)p);
18 if (cmp > 0) { /* key > p: move right */
19 base = (char *)p + size;
20 lim--;
21 } /* else move left */
22 }
23 return (NULL);
24 }