我读了数据结构手册中的二进制搜索的伪代码,然后开始编写代码。我写的代码是:二进制搜索的逻辑
#include <iostream.h>
#include <conio.h>
template <class T>
int BSearch(T x[], const int n, T item)
{
int loc, first = 0, found = 0, last = n-1;
while(first <= last && !found)
{
loc = (first + last)/2;
if(item < x[loc])
last = loc - 1;
else if(item > x[loc])
first = loc + 1;
else
found = 1;
}
return found;
}
int main()
{
const int n =5;
int x[n],item;
cout << "Pls enter " <<n<<" number(s): ";
for(int i = 0; i < n;i++)
cin >> x[i];
cout << "Pls enter the item to Search: ";
cin >> item;
if(BSearch(x,n,item))
cout << "\n\t Item Exist";
else
cout << "\n\t Item NOT Exist";
getch();
return 0;
}
没有任何错误,但是存在逻辑错误。它只是从BSearch函数返回0值,我只是得到这个消息“Item Not Exist”。我的错误在哪里?我没有找到它。 谢谢
当你用调试器加入代码时发生了什么? –
@irrelephant:在书中作者说“last < - loc -1” –
请注意,在_Sorting and Searching_的6.2.1节中,Knuth记录了第一个二进制搜索例程于1946年发布,但第一个发布的二进制搜索没有错误的程序直到1962年才出现。令人惊讶地很难得到正确的二进制搜索! –