Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

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