说明:元素必须是有序的,如果是无序的则要先进行排序操作。
1 # 二分查找 2 def binary_search(array, item): 3 low = 0 4 high = len(array) 5 while low <= high: 6 # 拿到中间下标 7 mid = (low + high) // 2 # 向下取整也可以使用int(x)的形式 8 guess = array[mid] 9 if guess == item: 10 return mid 11 if guess > item: 12 high = mid - 1 13 else: 14 low = mid + 1 15 return None 16 17 18 my_list = [1, 3, 4, 6, 7, 8, 9] 19 print(binary_search(my_list, 9)) # 6