非递归方式
def binary_search(alist,item):
n = len(alist)
start = 0
end = n - 1
while start < = end:
mid = (start + end) // 2
if item == alist[mid]:
return True
elif item < alist[mid]:
end = mid - 1
elif item > alist[mid]:
start = mid + 1
return False
递归方式
def binary_search2(alist, item):
n = len(alist)
if n == 0:
return False
mid = n // 2
if item == alist[mid]:
return True
elif item < alist[mid]:
return binary_search2(alist[:mid], item)
else:
return binary_search2(alist[mid+1:], item)