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)
归档时间: |
|
查看次数: |
67 次 |
最近记录: |