| | | | | |

Generic Binary Search

template <class I, typename T, class P>
I g_lower_bound (I beg, I end, const T& val, const P& LessThan)
// pre:    I is a random access iterator (operator [] and "pointer" arithmetic)
//         I has value_type T
//         beg + n = end for some n >= 0
//         beg[0] ... beg[n-1] are in non-decreasing order using LessThan
// post:   no state is changed
// return: itr = beg + i, where beg[i-1] < val <= beg[i]; or
//         itr = end if no such i exists
{
  I low = beg;
  I hih = end;
  I mid;

  while (low != hih)
  {
    mid =  low + (hih - low) / 2;
    if (LessThan(*mid , val))
      low = ++mid;
    else
      hih = mid;
  }  
  return low;
}

| | Top of Page | 8. Generic Algorithms - 10 of 12