如何用Python实现基本的二分查找算法?

问题描述 投票:0回答:1

我正在尝试在 Python 中实现排序列表的二分搜索算法。我编写了以下代码,但它似乎没有按预期工作。有人可以帮助我找出问题并提出纠正建议吗? 这是我的代码......

python algorithm search binary basic
1个回答
0
投票

我没有看到你的任何代码,但是这里有一个二叉搜索树算法的示例。

def binary_search(arr, target):
    low, high = 0, len(arr) - 1

    while low <= high:
        mid = (low + high) // 2
        mid_val = arr[mid]

        if mid_val == target:
            return mid  # Target found, return the index
        elif mid_val < target:
            low = mid + 1  # Adjust the search range to the right half
        else:
            high = mid - 1  # Adjust the search range to the left half

    return -1  # Target not found

# Example usage:
sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target_value = 7

result = binary_search(sorted_list, target_value)

if result != -1:
    print(f'Target {target_value} found at index {result}')
else:
    print(f'Target {target_value} not found in the list')
© www.soinside.com 2019 - 2024. All rights reserved.