xref: /reactos/sdk/lib/crt/search/bsearch.c (revision c2c66aff)
1 /* Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details */
2 #include <stdlib.h>
3 
4 /*
5  * @implemented
6  */
7 void *
8 __cdecl
bsearch(const void * key,const void * base0,size_t nelem,size_t size,int (__cdecl * cmp)(const void * ck,const void * ce))9 bsearch(const void *key, const void *base0, size_t nelem,
10 	size_t size, int (__cdecl *cmp)(const void *ck, const void *ce))
11 {
12   char *base = (char *)base0;
13   size_t lim;
14   int cmpval;
15   void *p;
16 
17   for (lim = nelem; lim != 0; lim >>= 1)
18   {
19     p = base + (lim >> 1) * size;
20     cmpval = (*cmp)(key, p);
21     if (cmpval == 0)
22       return p;
23     if (cmpval > 0)
24     {				/* key > p: move right */
25       base = (char *)p + size;
26       lim--;
27     } /* else move left */
28   }
29   return 0;
30 }
31