我正在尝试搜索包含以下内容的排序列表
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中的返回值
答案 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