Python二分查找
1. 非递归实现
def binary_search(alist, item):
first = 0
last = len(alist) - 1
while first <= last:
mid_point = (first+last)//2
if alist[mid_point] == item:
return True
elif item < alist[mid_point]:
last = mid_point - 1
else:
first = mid_point + 1
return False
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13))
False
True
2. 递归实现
def binary_search2(alist, item):
if len(alist) == 0:
return False
else:
mid_point = len(alist)//2
if alist[mid_point] == item:
return True
else:
if item < alist[mid_point]:
return binary_search2(alist[:mid_point], item)
else:
return binary_search2(alist[mid_point+1:], item)
testlist2 = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(binary_search2(testlist2, 3))
print(binary_search2(testlist2, 13))
总结:
最优时间复杂度 |
最坏时间复杂度 |
O(1) |
O(logn) |