在二进制搜索期间检查的索引

indices examined during binary search

本文关键字:检查 索引 二进制 搜索      更新时间:2023-10-16

我正在阅读我的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。