Guest User

Untitled

a guest
Jun 24th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. /* Created by: Justin Meiners (2017)
  2. */
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <time.h>
  7.  
  8. static inline int Int_Compare(const void *a, const void* b)
  9. {
  10. return ( *(int*)a - *(int*)b );
  11. }
  12.  
  13. #define BINARY_SEARCH(T, CMP) \
  14. \
  15. static inline T* BinarySearch_##T(const T* key, const T* sortedList, size_t count) \
  16. { \
  17. size_t start = 0; \
  18. size_t end = count; \
  19. while (start < end) \
  20. { \
  21. size_t mid = start + (end - start) / 2; \
  22. int cmp = CMP(key, sortedList + mid); \
  23. if (cmp > 0) \
  24. start = mid + 1; \
  25. else if (cmp < 0) \
  26. end = mid; \
  27. else \
  28. return (T*)(sortedList + mid); \
  29. } \
  30. return NULL; \
  31. }
  32.  
  33. BINARY_SEARCH(int, Int_Compare);
  34.  
  35. int main(int argc, const char* argv[])
  36. {
  37. clock_t start, end;
  38. int count = 5000000;
  39. int range = 10000000;
  40.  
  41. int* list = malloc(count * sizeof(int));
  42. int* toFind = malloc(range * sizeof(int));
  43. int* found = malloc(range * sizeof(int));
  44.  
  45. start = clock();
  46.  
  47. for (int i = 0; i < count; ++i)
  48. list[i] = rand() % range;
  49.  
  50. for (int i = 0; i < range; ++i)
  51. toFind[i] = rand() % range;
  52.  
  53. // sort the list for searching
  54. qsort(list, count, sizeof(int), Int_Compare);
  55.  
  56. end = clock();
  57. printf("sorting done %f\n", (end-start)/(double)CLOCKS_PER_SEC);
  58.  
  59. start = clock();
  60. for (int i = 0; i < range; ++i)
  61. {
  62. int* v = BinarySearch_int(toFind + i, list, count);
  63. found[i] = (v) ? *v : 0;
  64. }
  65. end = clock();
  66.  
  67. // do something with the result so compiler doesnt optimize it away
  68. // also convfirm they are working the same
  69. unsigned long sum = 0;
  70. for (int i = 0; i < range; ++i)
  71. sum += found[i];
  72. printf("%lu \n", sum);
  73.  
  74. printf("custom time: %f\n", (end-start)/(double)CLOCKS_PER_SEC);
  75.  
  76. start = clock();
  77. for (int i = 0; i < range; ++i)
  78. {
  79. int* v = bsearch(toFind + i, list, count, sizeof(int), Int_Compare);
  80. found[i] = (v) ? *v : 0;
  81. }
  82. end = clock();
  83.  
  84. printf("bsearch time: %f\n", (end-start)/(double)CLOCKS_PER_SEC);
  85.  
  86. sum = 0;
  87. for (int i = 0; i < range; ++i)
  88. sum += found[i];
  89. printf("%lu \n", sum);
  90.  
  91. return 1;
  92. }
Add Comment
Please, Sign In to add comment