在排序列表中搜索项目的二进制函数始终返回-1

时间:2019-04-06 15:02:27

标签: python list

我正在尝试搜索包含以下内容的排序列表

sortedList=[2,5,7,9,11,17,222]

问题:不幸的是,我编写的代码始终返回-1

import math

def binarySearch(li, ele):
    lowest = 0
    highest = len(li)-1
    index = -1
    while highest>=lowest and index==-1:
        mid = int(math.floor((highest+lowest)/2.0))
        if li[mid]==ele:
            index = mid
        elif li[mid]<ele:
            highest = mid-1
        else:
            lowest = mid+1

    return index

sortedList=[2,5,7,9,11,17,222]
print(binarySearch(sortedList,11))

预期结果: 给定整数的索引在sortedList中的返回值

1 个答案:

答案 0 :(得分:1)

有一个逻辑错误。只需将<更改为>即可。

while highest>=lowest and index==-1:
    mid = int(math.floor((highest+lowest)/2.0))
    if li[mid]==ele:
        index = mid
    elif li[mid] > ele:  # this line
        highest = mid-1
    else:
        lowest = mid+1