小黑算法成长日记26 二分查找

it2022-12-30  65

# 二分查找 arr = [1, 7, 9, 11, 12, 12, 23, 43, 43, 43, 44, 45, 55, 65, 67, 67, 77, 89] # 有序数组 def bin_search(arr,key): low = 0 # 最低指针 high = len(arr) - 1 # 最高指针 while low <= high: mid = (low + high) // 2 # 取中间值 if arr[mid] == key: return mid if key < arr[mid]: high = mid - 1 else: low = mid + 1 return -1 # 没有找到key print(bin_search(arr,11))

输出: 3

最新回复(0)