Calculating midpoint index in binary search

前端 未结 3 767
無奈伤痛
無奈伤痛 2021-02-05 22:26

So, the correct way of calculating mid in a binary search is mid = low + ((high - low) / 2) in order to handle overflow errors.

My implementati

3条回答
  •  情深已故
    2021-02-05 23:06

    Don Knuth's method works perfectly through a bitmask with no possibility of an overflow:

    return (low & high) + ((low ^ high) >> 1)
    

提交回复
热议问题