The correct code for Binary Search would be:
while (l < r) {
int m = (l + r) / 2;
if (A[m] == X) {
return m;
}
if (A[m] > X) {
r = m - 1;
}
else if (A[m] < X) {
l = m + 1;
}
}
return -1;
Just place the ‘found’ condition before any other condition in the loop, and you’re good to go!
solved Binary Search refactor [closed]