在二进制搜索期间检查的索引
indices examined during binary search
我正在阅读我的C++书,我有一个关于二进制搜索的问题。有一个称为critter
的数组,其中填充了(按顺序)={auk, bat, cow, eel, elk, fox, gnu, pig, rat}
所以,如果我想找到鳗鱼,我相信会根据我书中给出的公式,通过指数4->1->2->3。但是,如果你想搜索不在数组中的东西,该怎么办?
书告诉我算法是
set found = false
set first = 0
set last = n - 1 (n being the number of elements)
while first <= last and !found do following:
a) Calc loc = (first+last)/2
b) if item < a[loc] then
set last = loc - 1
else if a[loc] > item then
set first = loc + 1
else
set found = true
end while
因此,如果项目不在那里,它会跳到find=true吗,因为它不可能是<或>?或者它会遍历数组中的每个索引吗?
您会注意到,当first
不小于last
:while first <= last
时,循环将退出。
如果在find设置为true之前发生这种情况,则返回false。
相关文章:
- 如何检查类实例向量的索引是否为空
- 对于检查 >=0 终止条件时的循环索引类型
- C++如何获取索引I处的元素,并检查它在向量或数组中是否为空
- C++:检查向量中的元素是否大于另一个具有相同索引的元素的有效方法?
- 如何检查数组中的索引是否为空
- 有没有办法创建一个花哨的迭代器和相应的新数组,以便检查每个索引的索引值的条件?
- 如何检查向量是否包含指定索引中的特定字符
- 数组 1D 我需要要求用户检查索引和打印值
- 检查字符串是否包含从索引到另一个索引的字符串
- 检查二维数组中的相邻索引
- 检查动态数组的索引是否为空
- 检查数组的所有索引中是否存在值
- 如何检查具有确定值的指针数组的索引
- g++中用于检查数组索引的任何调试标志
- 如何使用 testBit 函数检查二进制数组中的特定索引位
- 如何检查数组索引是否存在
- 在二进制搜索期间检查的索引
- 在同一if语句中检查nullptr和有效索引
- 检查无符号整数是否没有索引的最佳实践
- 为什么 QList::at() 不检查索引是否存在并返回只读值?