I am trying to understand how binary search works. The basic code, for anyone who doesn't know, is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
My question is, will a binary search fail or access garbage memory if low equaled mid instead of mid + 1? Or is it just really inefficient?