我不知道为什么这不会返回密钥,它似乎跳过了这一步,我觉得逻辑是直的,如果 midptr 小于 key 则向右搜索,否则向左侧搜索。但它没有返回键,它返回-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;
}