我怎样才能使二进制搜索方法为 return false?

How can I get the binary search method to return false?

我正在使用 C# 中的二进制搜索方法作为练习,如果数字在列表中,它 return 为 true,但如果号码不在列表中。如果最后条件是 UB = LB,我曾考虑过做其他事情,但 SearchKey 不等于 MP。有什么建议吗?

static bool search(List<int> numbers, int searchKey)
    {
        int UB = numbers.Count - 1;
        int LB = 0;
        int MP = (UB + LB) / 2;

        bool done = false;
        do
        {
            if (numbers[MP] > searchKey)
            {
                UB = MP - 1;
                MP = (UB + LB) / 2;
            }
            else if (numbers[MP] < searchKey)
            {
                LB = MP + 1;
                MP = (UB + LB) / 2;
            }
            else if (numbers[MP] == searchKey)
            {
                done = true;
                return true;
            }
            else
            {
                done = true;
                return false;
            }
        } while (!done);
        return false;
    }

在你的 while 循环中添加这个条件 while (!done && LB < UB);

当没有项目被搜索时它运行无限时间