I've below code snippet, A
is non-decreasing order and need to check if X
is present in A
. If X
is present in A
then return position of occurrence of X
in A
otherwise returns -1. This code is not correct for some inputs, and need to fix it. Utmost I can modify 3 lines.
class Checking{
int check(int[] A, int X) {
int N = A.length;
if (N == 0) {
return -1;
}
int l = 0;
int r = N - 1;
while (l < r) {
int m = (l r) / 2;
if (A[m] > X) {
r = m - 1;
} else {
l = m;
}
}
if (A[l] == X) {
return l;
}
return -1;
}
}
I couldnt figure out the fix, any suggestions will be helpful ?
CodePudding user response:
Wiki page says that for such implementation of binary search middle element should be calculated using ceiling, so you can change to
int m = (l r 1) / 2;