【发布时间】:2017-05-13 11:46:17
【问题描述】:
所以,我只是处于初学者级别并尝试运行此二进制搜索代码。但是我的代码只将列表“只划分一次”并给出了答案。如何让它循环直到找到中点并将索引值作为输出。
user_input = (int(input("Enter a number you want to find : ")))
lister = [i for i in range(1,100)]
def bi_search(a,user):
low = 0
high = len(a)
mid = int(low + (high-low)/2)
while True:
if user < a[mid]:
low = 0
high = mid-1
mid = int(low + (high-low)/2)
print("Your number is in left half")
print("Your number is",mid,"thelement in the list")
break
elif user > a[mid]:
low= mid+1
high = len(a)
mid = int(low + (high-low)/2)
print("Your number is in right half")
print("Your number is",mid,"th element in the list")
break
bi_search(lister,user_input)
【问题讨论】:
-
while循环中的逻辑不正确,只需要保留
high = mid-1和low= mid+1这两行即可。
标签: python algorithm python-2.7 python-3.x binary-search