【发布时间】:2014-11-13 04:43:22
【问题描述】:
我正在尝试创建一个二分搜索功能。我用来测试的数组是: {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
- 42 应在第一次传递时作为索引返回。
- 应在第四次传递时将 1 作为索引返回。
两者都返回 index = -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;
}
【问题讨论】:
-
我怀疑使用
std::lower_bound会被视为作弊。 -
Ummm... 42 的索引为 10。所以它不会在第一次通过时找到它。
-
19/2 = 9.5 被截断为 9,因为您将其填充为整数。第一次通过时找不到它,因为它在索引 10 处。
标签: c++ search binary binary-search