2
我正在使用C#中的二进制搜索方法作为练习,如果数字在列表中,它将返回true,但如果数字不在列表中,则无法返回false。如果最后的条件是UB = LB,但SearchKey不等于MP,那么我曾考虑过这样做。有什么建议么?如何获得二进制搜索方法返回false?
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;
}
永远不会执行了'else'块,这三个中的至少一个,如果条件永远 –
'bool done = false;'把它放在里面做,而 –
在你的while循环中加入这个条件'while(!done && LB