我正在使用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;
}
1 回答
在你的while循环中添加这个条件
while (!done && LB < UB);
当没有项目搜索时,它运行无限时间