gpt4 book ai didi

algorithm - 这个二进制搜索的伪代码是否正确?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:53 24 4
gpt4 key购买 nike

Boolean Binary Search (first,last)
if (last > first)
return false
else
Set middle to (first+last)/2
Set result to list[middle].compareTo(item)
if (result is equal to 0)
return true
else
if (result < 0)
Binary Search (first, middle - 1)
else
Binary Search(middle + 1, last)

“O”代表什么?如果是我们要查找的项目,是否需要将这段伪代码中的'If(result < O)'替换为'If(result > O)'?

最佳答案

此代码包含一个非常微妙的错误:(first + last)/2 如果 firstlast 之和可能会导致溢出> 大于最大支持值。

更好的选择是使用 first + (last - first)/2

您可以在这里阅读更多相关信息: https://research.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html

关于algorithm - 这个二进制搜索的伪代码是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48245657/

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