编辑代码

def binary_search(arr, target):
    left, right = 0, len(arr) - 1

    while left <= right:
        mid = left + (right - left) // 2

        if arr[mid] == target:
            return mid  # 找到目标元素,返回索引
        elif arr[mid] > target:
            right = mid - 1  # 更新右边界
        else:
            left = mid + 1  # 更新左边界

    return -1  # 目标元素不存在


arr = [6, 17, 25, 34, 52, 63, 85]
target = 6

result = binary_search(arr, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the array.")