繁体   English   中英

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

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

我正在研究 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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM