如果键等于lst[mid]
,我试图使用return mid返回二进制搜索中的位置,但是却给出None。我可以中途打印:
def binary_search(lst,l,r,key):
print (lst[l:r])
mid = (l + r) // 2
if key == lst[mid]:
print([lst[mid]])
#print(mid)
return mid
elif key > lst[mid]:
l = mid + 1
binary_search(lst,l,r,key)
else:
r = len(lst[:mid])
binary_search(lst,l,r,key)
list = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
print(binary_search(list, 0, len(list), 14 ))
答案 0 :(得分:5)
递归调用binary_search
时,您需要返回结果。例如:
def binary_search(lst,l,r,key):
print (lst[l:r])
mid = (l + r )//2
if key == lst[mid]:
print ([lst[mid]])
#print (mid)
return mid
elif key > lst[mid]:
l = mid + 1
return binary_search(lst,l,r,key) # return me
else:
r = len(lst[:mid])
return binary_search(lst,l,r,key) # and me