我的递归二进制搜索在哪里出错?

时间:2017-03-14 12:12:35

标签: python

def BinarySearch(aList, first, last, target):

    assert 0 <= first < len(aList); last < len(aList)

    if len(aList) == 0:
        return False
    pos = first + last / 2
    pos = round(pos)
    if aList[pos] == target:
        return pos
    else:
        if target <= aList[pos]:
            return BinarySearch(aList[:pos], first, pos, target)
        else:            
            return BinarySearch(aList[pos +1 :], pos + 1, last, target)

这是一个学校问题,参数是通过另一个函数输入的。测试函数传递一个包含6个值的数组,我的代码找到前3个而不是最后的3个。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

def BinarySearch( aList, first, last, target ):

    if first < 0 or last < 0 or first > last or first >= len(aList):
        return -1

    if len( aList ) == 0:
        return -1
    pos = (first + last) // 2
    if aList[pos] == target:
        return pos
    elif aList[pos] > target:
        return BinarySearch( aList, first, pos - 1, target )
    else:            
        return BinarySearch( aList, pos + 1, last, target )