Skip to main content
2 of 3
added 3 characters in body; edited tags
Cris Luengo
  • 6.2k
  • 1
  • 13
  • 36

C++ Binary Search

Could you advice on this binary search implementation?

template<typename Iterator, typename T>
Iterator binarySearch(Iterator begin, Iterator end, const T& v) {
    Iterator low = begin;
    Iterator high = end - 1;
    while (low <= high)
    {
        Iterator mid = low + (high - low) / 2;
        if (*mid == v) {
            return mid;
        }
        else if (*mid < v) {
            low = mid + 1;
        } else {
            if (mid == begin) { 
                return end;
            }
            high = mid-1;
        }
    }
    return end;
}

The mid==begin line is unfortunate but cannot think of a more elegant approach here, welcoming ideas.

acd
  • 107
  • 4