gpt4 book ai didi

python - 二分查找 Python 为什么我们使用 mid + 1 或 mid - 1

转载 作者:太空宇宙 更新时间:2023-11-03 14:31:26 24 4
gpt4 key购买 nike

我正在学习二分搜索,示例代码使用“low = mid +1 and high = mid -1”,但我不明白为什么我们不使用“low =中和高=中 ”而不是?

def binarysearch(sequence, value):
lo, hi = 0, len(sequence) - 1
while lo <= hi:
mid = (lo + hi) // 2
if sequence[mid] < value:
lo = mid + 1
elif value < sequence[mid]:
hi = mid - 1
else:
return mid
return None

my_list = [1, 3, 5, 7, 9]
binarysearch(my_list, 3)

最佳答案

原因是为了避免重叠搜索;它将搜索范围的边界放置在尚未检查的项目上。

例如:如果 mid 位于索引 10,则左侧的下一个搜索将查找索引 9 之前的值,右侧的搜索将从索引 11 处的值开始。

                    mid
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| | | |
<-from 0 to mid-1-> <-- from mid+1 to the end -->

note that in this example, the boundary values are included

关于python - 二分查找 Python 为什么我们使用 mid + 1 或 mid - 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47256647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com