candyapplecorn

Template Recursive Binary Search

Apr 16th, 2015
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.56 KB | None | 0 0
  1. // For when normal binary search takes too many lines of code
  2. // when first called, lmin should be the least element, 0
  3. // and lmax should be v.size() - 1, and v should be sorted ascending
  4. template<class T>
  5. int recursiveBinarySearch(vector<T> v, T target, int lmin, int lmax){
  6.    
  7.     int middle = (lmin + lmax) / 2;
  8.  
  9.     lmin = v[middle] < target ? middle + 1 : lmin;
  10.     lmax = v[middle] >= target ? middle - 1 : lmax;
  11.  
  12.     return v[middle] == target ? middle : lmin > lmax ? -1 : recursiveBinarySearch(v, target, lmin, lmax);
  13. }
Advertisement
Add Comment
Please, Sign In to add comment