我想創建一個二進制搜索功能。我用來測試的陣列是: {1,4,5,6,9,14,21,28,31,35,42,46,50,53,57,62,63,65,74,89 }C++二進制搜索功能
現在我想我已經涵蓋了所有的邊界問題,但搜索1和42回來,因爲沒有找到我無法解釋的。
注意:如果索引= -1,這意味着該searchKey尚未陣列
- 42中發現應在第一遍被返回作爲索引。
- 1應作爲第四通的索引返回。
都返回作爲索引= -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'](http://en.cppreference.com/w/cpp/algorithm/lower_bound)將被認爲是作弊。 – WhozCraig 2014-09-18 18:11:50
嗯... 42有索引10.所以它不會在第一遍中找到它。 – RockOnRockOut 2014-09-18 18:14:33
19/2 = 9.5,因爲你將它填充到整數中,所以它被截斷爲9。它在第一遍中找不到,因爲它在索引10處。 – SnowInferno 2014-09-18 18:18:47