Amanda
Amanda

Reputation: 2143

Not getting the binary search algorithm correct

I am trying to implement binary search and I did the following:

function bs(a,x) {
    // a : array to look into
    // x : number to find
    let mpoint = Math.floor(a.length / 2);
    if(x >= a[mpoint]) {
        if(x == a[mpoint]) { return mpoint;}
        else {
            return bs([...a].slice(mpoint,a.length), x)
        }
    }else {
        if(x == a[mpoint]) {return mpoint;}
        else {
            return bs([...a].slice(0,mpoint),x)
        }
    }
}


bs([ 2, 3, 4, 10, 40 ], 10)

But I get an incorrect index as a result. What am I doing incorrectly?

Upvotes: 1

Views: 65

Answers (1)

Shuki Avraham
Shuki Avraham

Reputation: 1043

Try to change:

return bs([...a].slice(mpoint,a.length), x)

to:

return bs([...a].slice(mpoint,a.length), x) + mpoint

Upvotes: 4

Related Questions