My binary search is for finding a position for ordered insertion in a std::vector. However, it seems to me that it is performing one (or more?) too many comparisons to find that position. Particularly the ternary at the end. Have I designed this wrong? To be clear, I haven’t noticed any errors in output.
template<typename T>
size_t find(std::vector<T> data, T value) //returns position value should be inserted at
{
size_t start = 0;
size_t end = data.size();
if (!end) return 0;
size_t diff;
while (diff = (end - start) / 2)
{
size_t mid = diff + start;
if (data[mid].value <= value)
{
start = mid;
}
else
{
end = mid;
}
}
return data[start].value <= value ? end : start;
}
In a binary search, you fundamentally have a three-way branch:
>,<and=. There’s no way of writing this in C++ withouttwo comparison operators, but I would expect any decent compiler
to optimize them into a single machine instruction for the
comparison, followed by two conditional branches on the results.