Binary Search algorithm implementations

后端 未结 2 920
旧巷少年郎
旧巷少年郎 2020-12-10 09:35

I have come across multiple problems which use variations of binary search to reach the final answer. These problems include finding floor of square root of

2条回答
  •  有刺的猬
    2020-12-10 10:17

    Well, you can make it work in lots of ways, but:

    1) I use low=0, high=arr.length. If I'm going to call variables low and high, then I want low<=high always, even at the end of the search. This is also easier to think about when arr.length==0

    2) while (low. This corresponds to the answer for (1). When the loop is done, I like low==high, so I don't have to worry about which one to use.

    3) Always use mid=low+(high-low)/2 or mid = low+((high-low)>>1). The other option overflows when the array gets too long and gives negative results.

    4) This depends on what kind of comparison you're using (3-state vs. 2-state output), in addition to the other answers. For 2-state compares and the above-answers, you get low=mid+1 or high=mid. This is ideal, since it's obvious that the range gets smaller every iteration -- mid+1 > low obviously, and mid < high, because low (that's the loop condition) and (high-low)/2 rounds downward.

提交回复
热议问题