Binary Search algorithm implementations

后端 未结 2 921
旧巷少年郎
旧巷少年郎 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<high). 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<high (that's the loop condition) and (high-low)/2 rounds downward.

    0 讨论(0)
  • 2020-12-10 10:20

    It's not like there are worse and better options that you've mentioned. Usually it just depends on a implementation, e.g. if you pass high=arr.length then you'd rather write while(low < high) than while(low <= high).

    In fact, some of those differences may have a meaning. If we consider binary search algorithm to find your X number in an array A and there will be some (not only one) elements equal to X, you can both find index of the first one or the last one - it depends on a implementation.

    0 讨论(0)
提交回复
热议问题