binary search middle value calculation

后端 未结 4 1677
野性不改
野性不改 2021-02-01 16:42

The following is the pseudocode I got from a TopCoder tutorial about binary search

binary_search(A, target):
   lo = 1, hi = size(A)
   while lo <= hi:
               


        
4条回答
  •  自闭症患者
    2021-02-01 17:10

    Although this question is 5 years old, but there is a great article in googleblog which explains the problem and the solution in detail which is worth to share.

    It's needed to mention that in current implementation of binary search in Java mid = lo + (hi - lo) / 2 calculation is not used, instead the faster and more clear alternative is used with zero fill right shift operator

    int mid = (low + high) >>> 1;

提交回复
热议问题