我讀了數據結構手冊中的二進制搜索的僞代碼,然後開始編寫代碼。我寫的代碼是:二進制搜索的邏輯
#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年纔出現。令人驚訝地很難得到正確的二進制搜索! –