在python中理解while循环

Dan*_*ny 0 python data-structures python-3.x

我是Python的新手,并试图学习算法,我想问一下,为什么low < hi在查看列表时使用它是逻辑错误,正确的逻辑操作是low <= hi什么,它阻止的边缘情况.

def binary_search(input_array, value):
    """Your code goes here."""
    #O(log(n))
    low = 0
    hi = len(input_array) - 1 
    while low <= hi: #why cant it be low < hi
        mid = (low + hi)//2
        if input_array[mid] == value:
            return mid
        elif input_array[mid] < value:
            print(low, hi)
            low = mid + 1
        else:
            hi = mid - 1
    return -1


test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
print(binary_search(test_list, test_val1))
print(binary_search(test_list, test_val2))
Run Code Online (Sandbox Code Playgroud)

Jam*_*Maa 5

考虑到您只有一个元素,[1]而您正在搜索1.

< :return -1因为你只是跳过循环

<= :返回正确的值