Calculating mid in binary search

后端 未结 8 986
暖寄归人
暖寄归人 2020-11-29 17:34

I was reading an algorithms book which had the following algorithm for binary search:

public class BinSearch {
  sta         


        
8条回答
  •  温柔的废话
    2020-11-29 18:18

    Jeff suggested really good post to read about this bug, here is summary if you want quick overview.

    In Programming Pearls Bentley says that the analogous line "sets m to the average of l and u, truncated down to the nearest integer." On the face of it, this assertion might appear correct, but it fails for large values of the int variables low and high. Specifically, it fails if the sum of low and high is greater than the maximum positive int value (2^31 - 1). The sum overflows to a negative value, and the value stays negative when divided by two. In C this causes an array index out of bounds with unpredictable results. In Java, it throws ArrayIndexOutOfBoundsException.

提交回复
热议问题