bsearch.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /*
  2. * This file lifted in toto from 'Dlibs' on the atari ST (RdeBath)
  3. *
  4. *
  5. * Dale Schumacher 399 Beacon Ave.
  6. * (alias: Dalnefre') St. Paul, MN 55104
  7. * dal@syntel.UUCP United States of America
  8. * "It's not reality that's important, but how you perceive things."
  9. */
  10. #include <stdio.h>
  11. static int _bsearch; /* index of element found, or where to
  12. * insert */
  13. char *bsearch(key, base, num, size, cmp)
  14. register char *key; /* item to search for */
  15. register char *base; /* base address */
  16. int num; /* number of elements */
  17. register int size; /* element size in bytes */
  18. register int (*cmp) (); /* comparison function */
  19. {
  20. register int a, b, c, dir;
  21. a = 0;
  22. b = num - 1;
  23. while (a <= b) {
  24. c = (a + b) >> 1; /* == ((a + b) / 2) */
  25. if ((dir = (*cmp) (key, (base + (c * size))))) {
  26. if (dir < 0)
  27. b = c - 1;
  28. else /* (dir > 0) */
  29. a = c + 1;
  30. } else {
  31. _bsearch = c;
  32. return (base + (c * size));
  33. }
  34. }
  35. _bsearch = b;
  36. return (NULL);
  37. }