二分查找是一种快速查找列表中元素的算法,只可以作用在有序序列中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| def binary_search(alist, item): low = 0 high = len(alist) - 1 while low <= high: mid = (low + high) // 2 if alist[mid] > item: high = mid - 1 elif alist[mid] < item: low = mid + 1 else: return True return False
alist = [1, 2, 3, 4, 5] print(binary_search(alist, 1)) print(binary_search(alist, 3)) print(binary_search(alist, 5)) print(binary_search(alist, 7))
|