我在一本数据结构书籍中阅读了二进制搜索的伪代码,然后我开始编写代码。我写的代码是:
#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 值,我只是收到此消息“项目不存在”。我的虫子在哪里?!我没找到。谢谢