二分法python實現


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))

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM