1.非递归写法
def binary_search(arr, target):left, right = 0, len(arr) - 1while left <= right:mid = (left + right) // 2if arr[mid] == target: #如果相等return midelif arr[mid] < target:#当中值小于目标值 说明应该在右边查找了left = mid + 1 #把左索引 变成mid+1else:#当中值大于目标值 说明应该在左边查找了right = mid - 1 #把右索引 变成mid-1return False# 测试
arr = [1, 3, 5, 7, 9, 11, 13, 15]
target = 9
result = binary_search(arr, target)
print("元素在数组中的索引为:", result)
2.递归写法
def binary_search(alist, v, low, high):if low > high:return Falsemid = (low + high) // 2if alist[mid] == v:return midelif alist[mid] < v: #中间值比目标值小 说明应该在右边查找return binary_search(alist, v, mid + 1, high)else:#中间值比目标值大 说明应该在左边查找return binary_search(alist, v, low, mid - 1)# 测试testlist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(binary_search(testlist, 6, 0, len(testlist) - 1))