bsearch.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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(int argc, char* argv[]) {
  18. int x = 0;
  19. int y = 1024;
  20. int empty[] = {};
  21. BSEARCH_TEST_INT(x, empty, 0, NULL);
  22. int singleton[] = {42};
  23. printf("%p\n%p\n", singleton, &singleton[1]);
  24. BSEARCH_TEST_INT(x, singleton, 1, NULL);
  25. BSEARCH_TEST_INT(singleton[0], singleton, 1, &singleton[0]);
  26. BSEARCH_TEST_INT(y, singleton, 1, NULL);
  27. int two[] = {14, 42};
  28. BSEARCH_TEST_INT(x, two, 2, NULL);
  29. BSEARCH_TEST_INT(y, two, 2, NULL);
  30. BSEARCH_TEST_INT(two[0], two, 2, &two[0]);
  31. BSEARCH_TEST_INT(two[0], two, 1, &two[0]);
  32. BSEARCH_TEST_INT(two[1], two, 2, &two[1]);
  33. BSEARCH_TEST_INT(two[1], two, 1, NULL);
  34. int three[] = {-5, -1, 4};
  35. BSEARCH_TEST_INT(three[0], three, 3, &three[0]);
  36. BSEARCH_TEST_INT(three[1], three, 3, &three[1]);
  37. BSEARCH_TEST_INT(three[2], three, 3, &three[2]);
  38. int big[] = {-19, -13, -7, -3, 2, 5, 11};
  39. BSEARCH_TEST_INT(big[0], big, 7, big);
  40. BSEARCH_TEST_INT(big[6], big, 7, &big[6]);
  41. BSEARCH_TEST_INT(big[3], big, 7, &big[3]);
  42. BSEARCH_TEST_INT(x, big, 7, NULL);
  43. printf("PASS bsearch\n");
  44. return 0;
  45. }