我正在尝试创建二进制搜索功能。我用来测试的数组是: {1,4,5,6,9,14,21,28,31,35,42,46,50,53,57,62,63,65,74,89}
现在我认为我已经涵盖了所有的边界问题,但是找不到1和42的搜索,因为找不到我无法解释的内容。
注意:如果index = -1,则表示在数组中找不到searchKey
两者都返回索引= -1
int BinSearch(int data[], int numElements, int searchKey)
{
bool found = false;
int index;
int searchStart = 0;
int searchEnd = numElements - 1;
while (!found)
{
index = (searchEnd + searchStart) / 2;
// If searchEnd is next to searchStart then check both to see if either is
// searchKey
if ((searchEnd - 1) == searchStart)
{
found = true;
if (searchKey == data[searchStart]) {
index = searchStart;
}
else if (searchKey == data[searchEnd]) {
index = searchEnd;
}
else {
index = -1;
}
}
// If index is less than searchStart or greater than searchEnd then searchKey
// isn't in the array
else if (index <= searchStart || index >= searchEnd) {
found = true;
index = -1;
}
else if (searchKey > data[index]) {
searchStart = index + 1;
}
else if (searchKey < data[index]) {
searchEnd = index - 1;
}
else if (searchKey == data[index]) {
found = true;
}
}
return index;
}
答案 0 :(得分:0)
答案 1 :(得分:0)
改变这个:
if ((searchEnd - 1) == searchStart)
到此:
if ((searchEnd - 1) <= searchStart)
当查找1时,在第三次传递中,searchEnd将为3,searchStart将为0,因此index将为1.由于您的值位于位置0,因此它将在第一次传递中将searchEnd修改为等于0。