Ladies_Man

1_11 Binary search in seq.

Dec 15th, 2013
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.58 KB | None | 0 0
  1. unsigned long binsearch(unsigned long nel, int (*compare)(unsigned long i))
  2. {
  3.     unsigned long low = 0, high, mid;
  4.     high = nel-1;
  5.     while (low < high-1) {
  6.             mid = (low+high)/2;
  7.             if (compare(mid)>0)
  8.                 high = mid;
  9.             else
  10.                 if (compare(mid) < 0)
  11.                     low = mid;
  12.                 else
  13.                     if (compare(mid) == 0)
  14.                         return mid;
  15.  
  16.     }
  17.     if (compare(low) == 0) return low;
  18.     else
  19.         if (compare(high) == 0) return high;
  20.         else
  21.             return nel;
  22. }
Advertisement
Add Comment
Please, Sign In to add comment