def binarysearch(somelist,target):
lowindex=0
highindex=len(somelist)-1
while somelist[lowindex] != target and somelist[highindex] != target:
midindex = (highindex+lowindex) // 2
if target == somelist[midindex]:
print(somelist[midindex])
elif target < somelist[midindex]:
highindex=midindex-1
elif target > somelist[midindex]:
lowindex= midindex + 1
return -1
testlist=[0,1,2,8,13,17,19,32,42,15]
(binarysearch(testlist,2))
任何人都知道代码的错误似乎无法正常工作
答案 0 :(得分:0)
尝试此代码:如果找到Element,则返回1,否则为-1。
def b_search(target):
somelist = [0,1,2,8,13,17,19,32,42,15]
lowindex=0
highindex=len(somelist)-1
while lowindex <= highindex:
midindex = (highindex+lowindex) // 2
if target == somelist[midindex]:
return 1
elif target < somelist[midindex]:
highindex=midindex-1
elif target > somelist[midindex]:
lowindex= midindex + 1
return -1
print(b_search(11))
答案 1 :(得分:0)
只要while
位于第一个索引或target
循环中形成的任何子列表中的最后一个索引,您的二进制搜索功能就会停止while
循环。 / p>
您只需要检查低索引是否始终小于或等于高索引,然后运行while
循环。此外,找到元素后,您只需打印该元素并继续循环。那没有意义。您可以打印然后break
退出循环,或者只返回目标元素的索引(如果找到)。
所以,现在你的功能变成了:
def binarysearch(somelist, target):
lowindex = 0
highindex = len(somelist) - 1
while lowindex <= highindex:
midindex = (highindex+lowindex) // 2
if target == somelist[midindex]:
return midindex
elif target < somelist[midindex]:
highindex=midindex-1
elif target > somelist[midindex]:
lowindex= midindex + 1
return -1
所以,现在当你运行二进制搜索功能时,它会将元素2的索引返回为:
[IN]: print(binarysearch(testlist, 2))
[OUT]: 2