我創建的LEN 100二進制搜索計數器
li2 = list(range(100))
列表我用下面的二進制搜索功能,用一個計數器,但它需要5個搜索找到50應該找到它的第一次嘗試。 (100/2)= 50個LI2 [50] == 50
def binary_search(li,item):
low = 0
high = len(li)-1
trys = 0
while low<=high:
mid = int((low + high)/2)
guess = li[mid]
if guess == item:
return'Found',item, 'in', trys,'searches'
elif guess > item:
trys+=1
high = mid - 1
else:
trys+=1
low = mid + 1
return item,' not found', trys, ' searches attempted'
我運行binary_search(li2,50)
並返回下面
('Found', 50, 'in', 5, 'searches')
但如果高= LEN (list) – evan
>>> len(li2) >>> mid = int((100 + 0)/ 2) >>> li2 [mid] 50 – evan