我正在使用 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/