我正在尝试查找并修复此代码中的问题。它是通过递归实现的二进制搜索。我不知道它为什么会返回堆栈溢出和崩溃。
bool find( const int x, const int* pBegin, const int* pEnd)
{
int medel = (*pBegin +(( *pEnd-1) - *pBegin)/2) ;
if(x == medel)
return true ;
else if( x > medel)
{
int begin = (medel +1);
return find (x, &begin, pEnd);
}
else if( x< medel)
{
int last = (medel-1);
return find(x,pBegin, &last);
}
}
void main()
{
int arr[10];
for (int i=0;i<10;++i)
arr[i] = i;
bool hittat = find(7, &arr[0], &arr[9]);
cout << "hittat = " << hittat << endl;
system("pause");
}
当我调试代码时,我看到调用函数“find”时它采用了奇怪的参数,例如 this pic .
它应该使用 0 和 9,而不是这些巨大的数字:/ 我的指点有什么问题吗?
最佳答案
您应该计算指针 的平均值,并检查它们之间的元素走廊的值 是多少。相反,您计算它们所指向的值的平均值,这明显不同。
关于c++ - 递归二进制搜索实现正在崩溃......为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14540652/