Calculating mid in binary search

后端 未结 8 1023
暖寄归人
暖寄归人 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 17:55

    Here is an example, suppose you had a very big array of size 2,000,000,000 and 10 (10^9 + 10) and the left index was at 2,000,000,000 and the right index was at 2,000,000,000 + 1.

    By using lo + hi will sum upto 2,000,000,000 + 2,000,000,001 = 4,000,000,001. Since the max value of an integer is 2,147,483,647. So you won't get 4,000,000,000 + 1, you will get an integer overflow.

提交回复
热议问题