使用条件: 二分查找法适合用于不经常变动而查找频繁的有序列表。
1. 递归查找:
def binary_search(alist, item): """二分查找法:递归查找""" n = len(alist) if n > 0: mid = n // 2 if alist[mid] == item: return True elif item < alist[mid]: return binary_search(alist[:mid], item) else: return binary_search(alist[mid+1:], item) return False
2. 非递归查找:
first = 0 last = len(alist) - 1 mid = (first + last) // 2 while first <= last: if alist[mid] == item: return True elif item < alist[mid]: last = mid - 1 else: first = mid + 1 return False
文章来源: https://blog.csdn.net/weixin_40576010/article/details/88591212