bsearch.c 914 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. /*
  2. * This file originally 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. * Reworked by Erik Andersen <andersen@uclibc.org>
  11. */
  12. #include <stdio.h>
  13. void * bsearch (const void *key, const void *base, size_t num, size_t size,
  14. int (*cmp) (const void *, const void *))
  15. {
  16. int dir;
  17. size_t a, b, c;
  18. const void *p;
  19. a = 0;
  20. b = num;
  21. while (a < b)
  22. {
  23. c = (a + b) >> 1; /* == ((a + b) / 2) */
  24. p = (void *)(((const char *) base) + (c * size));
  25. dir = (*cmp)(key, p);
  26. if (dir < 0) {
  27. b = c;
  28. } else if (dir > 0) {
  29. a = c + 1;
  30. } else {
  31. return (void *)p;
  32. }
  33. }
  34. return NULL;
  35. }