Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The "+1" is not a superficial optimisation, it can be critical for correctness. Consider the following (correct) implementation, which uses +1:

    def binary_search(array, target):
        left, right = 0, len(array)
        while left < right:
            middle = (left + right) // 2
            if array[middle] < target:
                left = middle + 1
            else:
                right = middle
        return right
If you change `left = middle + 1` to `left = middle`, it hangs in an infinite loop!

(Explanation: when `left` and `right` differ by 1, `(left + right) // 2` will return `left` and the search will not make any progress.)



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: