bsearch.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. int int_cmp(const void* a, const void* b) {
  4. return *(const int*) a - *(const int*) b;
  5. }
  6. #define BSEARCH_TEST_INT(key, arr, len, expect) \
  7. do { \
  8. void* res = bsearch((const void*) &key, (void*) arr, len, sizeof(int), int_cmp); \
  9. if (res != expect) { \
  10. printf("FAIL bsearch for %d in [", key); \
  11. size_t i = 0; \
  12. for (; i < len; ++i) printf("%d,", arr[i]); \
  13. printf("] expected %p but got %p\n", (void*) expect, res); \
  14. return 1; \
  15. } \
  16. } while (0);
  17. int main(void) {
  18. int x = 0;
  19. int y = 1024;
  20. // TODO: Zero sized arrays are a non-standard GNU extension
  21. //int empty[] = {};
  22. //BSEARCH_TEST_INT(x, empty, 0, NULL);
  23. int singleton[] = {42};
  24. printf("%p\n%p\n", singleton, &singleton[1]);
  25. BSEARCH_TEST_INT(x, singleton, 1, NULL);
  26. BSEARCH_TEST_INT(singleton[0], singleton, 1, &singleton[0]);
  27. BSEARCH_TEST_INT(y, singleton, 1, NULL);
  28. int two[] = {14, 42};
  29. BSEARCH_TEST_INT(x, two, 2, NULL);
  30. BSEARCH_TEST_INT(y, two, 2, NULL);
  31. BSEARCH_TEST_INT(two[0], two, 2, &two[0]);
  32. BSEARCH_TEST_INT(two[0], two, 1, &two[0]);
  33. BSEARCH_TEST_INT(two[1], two, 2, &two[1]);
  34. BSEARCH_TEST_INT(two[1], two, 1, NULL);
  35. int three[] = {-5, -1, 4};
  36. BSEARCH_TEST_INT(three[0], three, 3, &three[0]);
  37. BSEARCH_TEST_INT(three[1], three, 3, &three[1]);
  38. BSEARCH_TEST_INT(three[2], three, 3, &three[2]);
  39. int big[] = {-19, -13, -7, -3, 2, 5, 11};
  40. BSEARCH_TEST_INT(big[0], big, 7, big);
  41. BSEARCH_TEST_INT(big[6], big, 7, &big[6]);
  42. BSEARCH_TEST_INT(big[3], big, 7, &big[3]);
  43. BSEARCH_TEST_INT(x, big, 7, NULL);
  44. printf("PASS bsearch\n");
  45. return 0;
  46. }