使用 Bool 函数在 C++ 中进行递归二叉搜索
recursive binary search in c++ using a bool function
我有一个学校分配,要求我创建一个递归的二叉搜索函数。我不允许更改函数签名。我对指针的经验不是最好的,我认为我的问题就在那里。我得到了一个堆栈流,但我真的不明白的方式
bool contains(const int* pBegin, const int* pEnd, int x)
{
int length = pEnd - pBegin;//gives me the length of the array
const int* pMid = pBegin + (length / 2);
if(length == 1)
{
if(*pMid != x)
return false;
return true;
}
else if(x < *pMid)
return contains(pBegin, pMid-1, x);
else
return contains(pMid, pEnd, x);
}
void main(){
setlocale(LC_ALL, "swedish");
int arr[10];
for(int i = 0; i < 10; ++i)
arr[i] = i;
bool find = contains(&arr[0], &arr[10], 3);//arr[10] points to the index after the array!
cout <<"found = "<< find << endl;
system("pause");
}
有人可以向我解释我做错了什么,以及我如何以更好的方式做到这一点吗?
堆栈溢出是由于太深的递归造成的。你的数组不太可能大到真正成为一个问题,所以你所拥有的是无限递归......contains() 不断调用自己,但无法检测到这一点。
看看这是怎么可能的,并添加断言。
您的代码假设 pend> pBegin
您的代码无法处理这种可能性。
#include <assert.h>
bool contains( ... )
{
assert(pBegin > pEnd);
...
现在,如果此假设不正确,它将中止。
(ppending> pBegin)为假有两种可能性,即"<"或"=="。在这两种情况下,您的代码会做什么?
下面剧透..
<块引用类>长度可以为零,并且不进行处理。
块引用类>相关文章:
- 按边长度递归搜索图中所有可行路径
- 在递归二叉搜索树中搜索
- 递归二进制搜索与字符串数组
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 如何改进搜索二项式系数的递归算法
- 使用后序遍历递归的深度优先搜索会产生意外输出
- 字符串的递归二进制搜索-C++
- 递归搜索n元树中的元素
- 这是河内算法的递归塔是一种不知情的搜索
- 二叉搜索树按级别递归C++打印节点
- 了解一种神秘地起作用的递归二进制搜索算法
- 在 c++ 中递归搜索注册表
- 我在DFS搜索(树)代码中遇到麻烦.我如何打破递归
- 双链接列表通过递归搜索C
- VPATH 中的递归搜索
- 修剪递归搜索路径
- 二叉树上的递归搜索返回真和假
- 在计算机中递归搜索文件
- 递归搜索不起作用
- c++递归搜索函数(学校作业)