我不明白为什么这不会返回键,它似乎跳过了一步,我觉得逻辑是直的,如果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