时间复杂度
最优时间复杂度:O(1) 最坏时间复杂度:O(logn)
思路
对有序的顺序表进行查找,以下标查找,每次取一半查找,如[1,2,3,4,5,6,7,8,9],查3, 下标从0~8,(0+8)//2=4,对比折半到下标为2的元素3,3<5,要查的3在5左边,再以同样的方法继续
查找元素4,下标是2:列表的下标是从0-8,所以折半的下标是(0+8)//2=4,要查找的元素4的下标2小于折半的下标4元素7,所以元素4在元素7的左边,再继续折半重复查找
代码实现
1,非递归实现
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
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(binary_search(testlist, 3)) # 返回False,未查找到
print(binary_search(testlist, 13)) # 返回True,查找到了
2,递归实现
def binary_search_2(alist, item):
"""二分查找:递归实现"""
if len(alist) == 0:
return False
else:
midpoint = len(alist)//2
if alist[midpoint] == item:
return True
else:
if item<alist[midpoint]:
return binary_search(alist[:midpoint],item)
else:
return binary_search(alist[midpoint+1:],item)
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(binary_search_2(testlist, 3)) # 返回False,未查找到
print(binary_search_2(testlist, 13)) # 返回True,查找到了