Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Search in an array corner case

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.

like image 204
TechnoCorner Avatar asked Aug 16 '19 19:08

TechnoCorner


1 Answers

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));
like image 73
Nina Scholz Avatar answered Oct 23 '22 05:10

Nina Scholz