I'm studying binary search algorithm and I've seen many times the algorithm written as follows (this is C++ but the language is not that important here):
int start = 0;
int end = vec.size() - 1;
do {
int mid = (lo + hi) / 2;
if (target < vec[mid])
start = mid + 1;
else if (target > vec[mid])
end = mid - 1;
else
// found
} while (start <= end);
However I've also seen implementations like this:
int start = 0;
int end = vec.size() - 1;
do {
int mid = (int)ceil((lo + hi) / 2.0);
if (target < vec[mid])
start = mid + 1;
else if (target > vec[mid])
end = mid - 1;
else
// found
} while (start <= end);
Both seem to work. Is there any correctness or performance reason why I should get the ceil
and do that second case floating point arithmetic instead of using the first version?