I'm trying to implement Binary search and everything works fine for all the numbers except the corner cases:
const a = [1,2,3,4,5];
function findNum(arr, num) {
    let start=0, end = arr.length-1, mid = Math.floor((start+end)/2);
    while(start <= end) {
        mid = Math.floor((start+end)/2);
        if(mid===num) return true;
        else if(mid > num) end = mid-1;
        else start = mid+1;
    }
    return false;    
}
console.log(findNum(a, 5));
When I search for "5" it returns false, as opposed to true. What I am I missing here?
All other cases work fine as expected.
You need to check the value, not the index.
const a = [1, 2, 3, 4, 5];
function findNum(arr, num) {
    let start = 0,
        end = arr.length - 1,
        mid = Math.floor((start + end) / 2);
    while (start <= end) {
        mid = Math.floor((start + end) / 2);
        if (arr[mid] === num) return true; // take value
        if (arr[mid] > num) end = mid - 1; // take value as well
        else start = mid + 1;
    }
    return false;
}
console.log(findNum(a, 0));
console.log(findNum(a, 1));
console.log(findNum(a, 2));
console.log(findNum(a, 3));
console.log(findNum(a, 4));
console.log(findNum(a, 5));
console.log(findNum(a, 6));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With