bsearch.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 *
  14. bsearch(key, base, num, size, cmp)
  15. register char *key; /* item to search for */
  16. register char *base; /* base address */
  17. int num; /* number of elements */
  18. register int size; /* element size in bytes */
  19. register int (*cmp) (); /* comparison function */
  20. {
  21. register int a, b, c, dir;
  22. a = 0;
  23. b = num - 1;
  24. while (a <= b)
  25. {
  26. c = (a + b) >> 1; /* == ((a + b) / 2) */
  27. if ((dir = (*cmp) ((base + (c * size)), key)))
  28. {
  29. if (dir > 0)
  30. b = c - 1;
  31. else /* (dir < 0) */
  32. a = c + 1;
  33. }
  34. else
  35. {
  36. _bsearch = c;
  37. return (base + (c * size));
  38. }
  39. }
  40. _bsearch = b;
  41. return (NULL);
  42. }