二进制搜索中的无限循环

时间:2014-01-30 06:24:17

标签: python infinite-loop binary-search

我正在尝试使用以下函数实现二进制搜索:

def buggy_binary_search(input, key):
    low = 0
    high = len(input)-1
    mid = (low + high)/2
    while low <= high:
        if input[mid] == key:
            return mid
        if input[mid] > key:
            high = mid - 1
        else:
            low = mid
    return -1

运行时的上述函数进入无限循环。我怎么能纠正这个?

3 个答案:

答案 0 :(得分:1)

因为,你没有更新mid的值,while循环继续检查相同的元素并进入无限循环,以纠正许多人指出的,更新mid in while循环。
此外,您应该low = mid+1而不是low = mid

完整代码如下: -

    def binary_search(input, key):
       low = 0
       high = len(input)-1
       mid = (low + high)/2
       while low <= high:
          mid = (low + high)/2
          if input[mid] == key:
             return mid
          if input[mid] > key:
             high = mid - 1
          else:
             low = mid + 1
       return -1

确保输入已排序!

答案 1 :(得分:0)

def binary_search(input, key):
    low = 0
    high = len(input)-1
    mid = (low + high)/2
    while low <= high:
       mid = (low + high)/2
       if input[mid] == key:
           return mid
       if input[mid] > key:
           high = mid - 1
       else:
           low = mid + 1
    return -1
正如Dmitry Bychenko所说,你应该把mid =(low + high)/ 2放在循环中。

答案 2 :(得分:0)

"""don't use "input" as a variable name. its a python keyword.
make sure your array is sorted
use integer division when computing midpoint
"""

def bsearch(input_array,target):
    lo,hi=0,len(input_array)-1
    while lo<=hi:
        mid=(lo+hi)//2
        if input_array[mid]==target:
            print "found at ",mid
            return mid
        if input_array[mid]>target:
            print "look left"
            hi=mid-1
        if input_array[mid]<target:
            print "look right"
            lo=mid+1
    return -1

a=[2,4,7,8,12,88,99,101]
target=7

assert bsearch(a,1134)==-1,"value 1134 isn't in array but says it is"
assert bsearch(a,2)==0,"value 2 is in the zero element of array.begenning"
assert bsearch(a,101)==7,"value 101 is in the 7th element of array. end"
assert bsearch(a,12)==4,"value 12 is in the 4th element of array. midpoint"