1. 程式人生 > >二分法python實現

二分法python實現

color python實現 spa 等號 def bin none 分法 list

def bin_search(list,item):
low=0
high=len(list)-1
while low<=high: #4
mid = round(((low + high) / 2)+0.1,0) #1
#mid=(low + high) / 2
guess=list[int(mid)]
if guess==item:
return int(mid)
if guess>item:
high=mid-1 #2
else:

low=mid+1 #3
return None

my_list=[1,3,5,7,9]
print(bin_search(my_list,7))

註意二分法的思想,實現中四處標記的原理,以及第四處加等號和不加等號的影響

二分法python實現