Calculating mid in binary search

后端 未结 8 979
暖寄归人
暖寄归人 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:20

    int mid=(l+h)/2; can lead to integer overflow problem.

    (l+u) gets evaluated into a large negative integer value and its half is returned. Now,if we are searching for an element in an array, it would lead to "index out of range error."

    However, the issue is resolved as:-

    • int mid=l+(h-l)/2;
    • Bit Manipulation: For faster computation->int mid=((unsigned int)l+(unsigned int)h) >> 1 ;

    where >> is the right shift operator.

    Hope this helps :)

    0 讨论(0)
  • 2020-11-29 18:22

    The problem is that (l+u) is evaluated first, and could overflow int, so (l+u)/2 would return the wrong value.

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