c# - 如何让二进制搜索方法返回 false?

标签 c# binary-search

我正在使用 C# 中的二进制搜索方法作为练习,如果数字在列表中,它返回 true,但如果数字不在列表中,我无法让它返回 false。如果最后条件是 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);

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

关于c# - 如何让二进制搜索方法返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33811488/

相关文章:

C# 设置文件 : Why do I have to use Settings. 默认值?

c# - 有关美国税收的特定编程问题(示例 : Zip+4 or City/State/etc. )

c# - 无法调试.NET Core : Could not load file or assembly 'System.运行时,版本=4.2.1.0/4.2.0.0

java - 使用 `Collections.binarySearch` 签名实现二进制搜索

java - 对字符串的特定部分进行二分查找

C#算法根据值确定人员分组

c# - ExecuteNonQuery() 抛出 "Incorrect syntax near the keyword ' 用户'”

c++ - 比有序列表的二进制搜索更快

c - 从已编译的搜索程序中提取记录,C

c++ - multimap 的时间复杂度问题