⼆分查找⼜称折半查找,优点是⽐较次数少,查找速度快,平均性能好;
其缺点是要求待查表为有序表,且插⼊删除困难。
因此,折半查找⽅法适⽤于不经常变动⽽查找频繁的有序列表。
1.⾸先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字⽐较,如果两者相等,则查找成功;
2.否则利⽤中间位置记录将表分成前、后两个⼦表,如果中间位置记录的关键字⼤于查找关键字,则进⼀步查找前⼀⼦表,否则进⼀步查找后⼀⼦表。
3.重复以上过程,直到找到满⾜条件的记录,使查找成功,或直到⼦表不存在为⽌,此时查找不成功。
方法一:非递归实现
def binary_search(list1, item):
start = 0
end = len(list1) - 1
while start <= end:
mid = (start + end) // 2
if list1[mid] == item:
return True
elif item < list1[mid]:
end = mid - 1
else:
start = mid + 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_search2(list1, item):
if len(list1) == 0:
return False
else:
mid = len(list1) // 2
if list1[mid] == item:
return True
else:
if item < list1[mid]:
return binary_search2(list1[:mid], item)
else:
return binary_search2(list1[mid + 1:], item)
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(binary_search2(testlist, 3))
print(binary_search2(testlist, 13))