时间复杂度最优O(1)
最差O(longn)
递归方法实现
def binary_search(alist,item):
n = len(alist)
if 0 == n:
return False
mid = n // 2
if alist[mid] == item:
return True
elif item < alist[mid]:
return binary_search(alist[:mid], item)
else:
return binary_search(alist[mid+1:], item)
if __name__ == "__main__":
# alist = [random.randint(0, 100) for i in range(8)]
alist = [0, 74, 45, 63, 97, 9, 47, 66]
print(alist)
print(binary_search(alist, 0))
print(binary_search(alist, 33))
非递归方法实现
def binary_search(alist, item):
first = 0
last = len(alist) - 1
while first <= last:
midpoint = (first + last) // 2
if alist[midpoint] == item:
return True
elif item < alist[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return False
if __name__ == "__main__":
# alist = [random.randint(0, 100) for i in range(8)]
alist = [0, 74, 45, 63, 97, 9, 47, 66]
print(alist)
print(binary_search(alist, 0))
print(binary_search(alist, 33))