Binary Search is a simple algorithm but is tricky when it comes to implementing it. The lower and upper bounds have to be set carefully to avoid those silly errors.
I personally prefer the iterative version to avoid unnecessary use of recursive calls.
Below is the standard algorithm
I personally prefer the iterative version to avoid unnecessary use of recursive calls.
Below is the standard algorithm
bool search(int x[], int n, int k) {
int l = 0, r = n-1;
while (l <= r) {
int m = (l+r)/2;
if (x[m] == k) return true;
if (x[m] < k) l = m+1; else r = m-1;
}
return false;
}
Now lets try to find the first element greater than given element
int search(int x[], int n, int k) {
int l = 0, r = n-1;
while (l <= r) {
int m = (l+r)/2;
if (x[m] < k) l = m+1;
else {
r = m-1;
index = m;
}
}
return index;
}
i will continue updating this post