二分法
二分法查找,就是在一个 有序的序列中,查找目标数值,比较目标值与序列中间值的大小,假设序列为递增序列,如果目标值与序列中间值相等,则退出(return True),如果目标值大于中间值,则在中间值右半部分序列中按照前面的方法递归搜索,否则在中间值左半部分序列中按照前面的方法递归搜索,递归终止条件:序列长度为1且完成比较。
算法实现
实现方法:递归法和循环法。
递归方法:
def bins1(lst, item):
idx = len(lst)//2
if item == lst[idx]:
return True
elif item > lst[idx]:
if len(lst) == 1:
return False
return bins1(list(lst[idx:]), item)
else:
if len(lst) == 1:
return False
return bins1(list(lst[:idx]), item)
循环方法:
def bins2(lst, item):
max1 = lst[0]
min1 = lst[-1]
if max1 < min1:
max1, min1 = lst[-1], lst[0]
if item > max1 or item < min1:
return False
tmp = lst[:]
idx = len(tmp)//2
while tmp:
if item == tmp[idx]:
return True
elif item > tmp[idx]:
tmp = tmp[idx:]
idx = len(tmp)//2
else:
tmp = tmp[:idx]
idx = len(tmp)//2
return False