利用Python写二分查找算法
2017-10-12 本文已影响0人
万越天
#!/usr/bin/env python
# _*_ encoding:utf-8 _*_
def binary_search(list,item):
low = 0
high = len(list)-1
while low<=high:
mid = (low+high)//2 # python2: mid = (low+high)/2
print(mid)
guess = list[mid]
if guess>item:
high = mid-1
elif guess<item:
low = mid+1
else:
return mid
return None
mylist = [1,3,5,7,9,10,11,13]
print(binary_search(mylist,5))