二分法
• 二分查找的前提是符号表中的记录必须有序。
• 在符号表中取中间记录作为比较对象,
○ 1. 若中间值和给定值相等,则查找成功;
○ 2. 若给定值小于中间值,则在左半区继续查找,否则在右半区进行查找;
○ 3. 不断重复直到成功或失败(循环)。
非递归实现
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))
print(binary_search(testlist, 13))
递归实现
def binary_search(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(testlist, 3))
print(binary_search(testlist, 13))
python实现二分法查找
最新推荐文章于 2024-09-14 10:00:00 发布