home *** CD-ROM | disk | FTP | other *** search
/ Atari FTP / ATARI_FTP_0693.zip / ATARI_FTP_0693 / Mint / mntlib32.zoo / bsearch.c < prev    next >
C/C++ Source or Header  |  1993-02-26  |  1KB  |  57 lines

  1. /* from Dale Schumacher's dLibs library */
  2.  
  3. #include <stddef.h>
  4. #include <stdlib.h>
  5. #include <assert.h>
  6.  
  7. /*
  8.  * This routine is safe in the sense that it does not make
  9.  * assumptions about sizeof(void *). Gcc assumes same as char *
  10.  * when not -ansi, the "other" compiler just barfs.
  11.  *
  12.  */
  13.  
  14. void * bsearch(key, base, num, size, cmp)
  15.     register const void * key;        /* item to search for */
  16.     register const void * base;        /* base address */
  17.     size_t          num;        /* number of elements */
  18.     register size_t   size;        /* element size in bytes */
  19.     /* comparison function */
  20.     register int (*cmp) __PROTO((const void *, const void *));
  21.     {
  22.     register size_t a, b, c;
  23.     register int dir;
  24.  
  25. #if 0
  26.     assert ((key != NULL) && (base != NULL) && (size > 0) && (num > 0) &&
  27.         (cmp != NULL));
  28. #else
  29.     if ((key == NULL) || (base == NULL) || (size == 0) || (num == 0) 
  30.         || (cmp == NULL))
  31.         return NULL;
  32. #endif
  33.  
  34.     a = 0;
  35.     b = num - 1;
  36.     while(a <= b)
  37.         {
  38.         c = (a + b) >> 1;    /* == ((a + b) / 2) */
  39.         if ((dir = (*cmp)((void *)((char *)base + (c * size)), key)) != 0)
  40.             {
  41.             if (dir > 0)
  42.             {
  43.                 if (c == 0)
  44.                 return(NULL);
  45.                 b = c - 1;
  46.             }
  47.             else /* (dir < 0) */
  48.                 a = c + 1;
  49.             }
  50.         else
  51.             {
  52.             return((void *)(((char *)base) + (c * size)));
  53.             }
  54.         }
  55.     return(NULL);
  56.     }
  57.