我不明白爲什麼這不會返回鍵,它似乎跳過了一步,我覺得邏輯是直的,如果midptr小於鍵,然後搜索右側,否則搜索左側。但它不返回鍵它返回-1。幫幫我?這裏是代碼和功能二元搜索使用遞歸
#include<iostream>
using namespace std;
int binsrch(int *raw, unsigned int size, int key);
int main()
{
int raw[] = {1,3,5,7,11,23, 48};
cout << binsrch(raw, 7, 11) << endl;
system("pause");
return 0;
}
int binsrch(int *raw, unsigned int size, int key)
{
int *begptr, *endptr ,*midptr;
//see if we already have the key
if(*raw == key)
return key;
begptr = raw;
endptr = raw + (size - 1);
midptr = raw + (size/2);
cout << "#" <<*midptr << " size:" << size<< endl;
if(*midptr == key)
{
return key;
}
else if(*midptr < key) //Search Right
{
cout << "#" <<*(midptr+1) << " size:" << size<< endl;
binsrch(midptr + 1, size/2, key);
}
else if(*midptr > key) //Search Left
{
cout << " #" <<*midptr << " size:" << size<< endl;
binsrch(begptr, size/2, key);
}
return -1;
}
@Paulpro:[C++版本](http://www.cplusplus.com/reference/algorithm/binary_search/)會更好;它是類型安全的並且可能更快。 – 2013-04-22 18:24:14
真棒謝謝大家! – user2206227 2013-04-22 18:31:44