1

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?

3
  • The if inside the else makes no sense since there is no way x can be equal in that section. Commented Jun 17, 2019 at 13:03
  • The index is correct but apparently it is of the sliced array. So add the mpoint. Commented Jun 17, 2019 at 13:05
  • The [...a] spread literal is superfluous, slice creates a new array anyway Commented Jun 17, 2019 at 13:07

1 Answer 1

4

Try to change:

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

to:

return bs([...a].slice(mpoint,a.length), x) + mpoint
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.