分页: 1 / 1

binary search中不明白的一点问题.

发表于 : 2013-02-28 12:38
drongh

代码: 全选

def search_binary(xs, target):
    """ Find and return the index of key in sequence xs """
    lb = 0
    ub = len(xs)
    while True:
        if lb == ub:   # If region of interest (ROI) becomes empty
            return -1

        # Next probe should be in the middle of the ROI
        mid_index = (lb + ub) // 2

        # Fetch the item at that position
        item_at_mid = xs[mid_index]

        # print("ROI[{0}:{1}](size={2}), probed='{3}', target='{4}'"
        #       .format(lb, ub, ub-lb, item_at_mid, target))

        # How does the probed item compare to the target?
        if item_at_mid == target:
            return mid_index      # Found it!
        if item_at_mid < target:
            lb = mid_index + 1     # Use upper half of ROI next time
        else:
            ub = mid_index        # Use lower half of ROI next time

Re: binary search中不明白的一点问题.

发表于 : 2013-02-28 13:16
枫叶饭团
已经查找过的数当然应该直接去掉啊

Re: binary search中不明白的一点问题.

发表于 : 2013-02-28 13:17
cuihao
必须有一个加一或减一吧。
比如吧,lb=3,ub=4时,mid是3,如果查找目标在4,而lb不加一,那么lb就永远是3,死循环了。

Re: binary search中不明白的一点问题.

发表于 : 2013-02-28 14:22
drongh
cuihao 写了:必须有一个加一或减一吧。
比如吧,lb=3,ub=4时,mid是3,如果查找目标在4,而lb不加一,那么lb就永远是3,死循环了。
刚刚调试了一下,对于目标在表中的,可以通过测试.
如果不在表中的,就是死循环,就像楼上说的,lb 永远不会等于 ub了