3 ms·
Your loop body looks incorrect. You're both adding 1 when updating low and subtracting 1 when updating high -- but you let the high index start at array.length.
by bla3 7y ago
Your loop body looks incorrect. You're both adding 1 when updating low and subtracting 1 when updating high -- but you let the high index start at array.length. It's possible that your additional || clause before the high update mitigates the effects of this, but it's at best inefficient. To implement binary search effectively, it's useful to think about invariants. https://zhu45.org/posts/2018/Jan/12/how-to-write-binary-search-correctly/ https://zhu45.org/posts/2018/Jan/12/how-to-write-binary-sear... looks like a decent post on this topic. Searching for "binary search loop invariant" or similar will find many similar articles. I recommend giving them a look, it's a useful thought framework for this algorithm :)
- bla3 7y agoThe highest-rated comment on https://stackoverflow.com/questions/504335/what-are-the-pitfalls-in-implementing-binary-search https://stackoverflow.com/questions/504335/what-are-the-pitf... is also good.
- claes-magnus 7y agoThank you!