Advertisement
_takumi

bsearch2

Jan 20th, 2023 (edited)
928
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. struct BSearchResult {
  4.     size_t low;
  5.     size_t high;
  6.     int result;
  7. };
  8.  
  9. struct BSearchResult
  10. bsearch2(const void *key, const void *base, size_t nmemb, size_t size,
  11.          int (*compar)(const void *p1, const void *p2, void *user),
  12.          void *user) {
  13.     size_t low = 0, high = nmemb - 1, mid;
  14.     struct BSearchResult res;
  15.     if (nmemb == 0) {
  16.         res.result = 0;
  17.         res.low = 0;
  18.         res.high = 0;
  19.         return res;
  20.     }
  21.     while (low <= high) {
  22.         mid = low + (high - low) / 2;
  23.         if (compar(key, base + size * mid, user) == 0) {
  24.             res.low = mid;
  25.             while (res.low != -1 &&
  26.                    compar(key, base + size * res.low, user) == 0) {
  27.                 res.low--;
  28.             }
  29.             res.low++;
  30.             res.high = mid;
  31.             while (res.high != nmemb &&
  32.                    compar(key, base + size * res.high, user) == 0) {
  33.                 res.high++;
  34.             }
  35.             res.result = 1;
  36.             return res;
  37.         } else if (compar(key, base + size * mid, user) > 0) {
  38.             low = mid + 1;
  39.         } else {
  40.             if (mid == 0) {
  41.                 low = 0;
  42.                 break;
  43.             }
  44.             high = mid - 1;
  45.         }
  46.     }
  47.     res.result = 0;
  48.     res.low = low;
  49.     res.high = low;
  50.     return res;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement