下面是一个使用Python语言实现二分法查找的示例代码:
def binary_search(arr, target): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 # 测试代码 arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] target = 6 result = binary_search(arr, target) if result != -1: print(f'找到目标元素在数组中的索引位置: {result}') else: print('未找到目标元素')
运行以上代码,输出结果为:找到目标元素在数组中的索引位置: 5。说明目标元素6在数组中的索引位置为5。