You are given a std::vector<T>
of distinct items. which is already sorted.
type T
only supports less-than <
operator for comparisons. and it is a heavy function. so you have to use it as few times as possible.
Is there any better solution than a binary search? If not, is there any better solution than this, that uses less-than operator fewer times?
template<typename T>
int FindKey(const std::vector<T>& list, const T& key)
{
if( list.empty() )
return -1;
int left = 0;
int right = list.size() - 1;
int mid;
while( left < right )
{
mid = (right + left) / 2;
if( list[mid] < key )
left = mid + 1;
else
right = mid;
}
if( !(key < list[left]) && !(list[left] < key) )
return left;
return -1;
}
It's not a real world situation, just a coding test.