如何解决递归二分查找 - C++
第一次在这里发帖,所以要温柔。我正在尝试执行递归二进制搜索。我尝试了不同的代码变体来尝试使函数工作,但我仍然没有。
这是我的代码:
bool contained(int x,const int* pBegin,const int* pEnd){
if(x==*pBegin) { //
return pBegin;
}
int size = pEnd - pBegin; //size of the array
int mid= size/2; //the middle of the array
int const* pMid = pBegin + mid; //The address of the element in the middle of the array
if(x>*pMid) //Condition that looks if x is to the left of the array
return contained(x,pMid,pEnd);
else if(x<*pMid) //Condition that looks if x is to the right of the array
return contained(x,pBegin,pMid-1);
}
int main()
{
cout << "Binary search,test: " << endl;
int arr[] = {1,2,3,4,5,7,8,9};
int size = 9;
for(int i=0; i<size; i+=1)
arr[i] = i;
bool find = containedInSortedarray(6,&arr[0],&arr[size]);
cout << "Found " << find << endl;
}
例如,当我使用预制数组执行包含 bool 的函数并让它搜索值 6 时,它最终应该得出该元素不存在的结论,但我的输出表明它存在。我是否遗漏了代码中的某些内容?
提前致谢!
解决方法
您的代码有几个问题:
- 你永远不会返回
false
。 - 您返回的
pBegin
不是布尔值,(不幸的是,在您的情况下)它可以隐式转换为 1,但也不是您想要的方式。一直打开编译器警告 --Wextra -Wall -pedantic -Werror
应该是最低要求,特别是如果您是初学者。 - 准确确定函数搜索的区间。
func(x,a,b)
- 是否包含b
?基于contained(x,pBegin,pMid-1);
似乎确实如此,但在containedInSortedarray(6,&arr[0],&arr[size]);
的情况下,希望不是。 - 取消引用
&arr[size]
是 UB。 - main 中 for 循环的目的是什么?
- 将大小从数组中分离出来是一场等待发生的灾难。至少使用
sizeof(arr)/sizeof(arr[0])
。更好的是,使用std::array
或std::vector
。
我建议搜索[a,b)
,因为它可以很容易地分为[a,mid)
、[mid,end)
。这样您的 mid
计算已经正确。然后你可以像 containedInSortedarray(x,arr,arr+arr_size)
基本条件应该捕获大小为 0 和 1 的数组 - 可以简单地测试两者是否存在 x
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。