二叉搜索功能始终返回 -1 值而不是索引
binary search fuction always returns -1 value instead of index
我的二进制搜索函数总是返回 -1 而不是索引,即使数据存在于数组中也是如此。谁能帮我找出问题
int main(){
int ar[10]={1,2,3,4,5,6,7,8,9,10};
int i,w;
cout<<"enter the element to search"<<endl;
cin>>w;
int y = binarysearch(ar,w,0,9);
cout<<y<<" index"<<endl;
return 0;
}
int binarysearch(int ar[],int x,int p,int r)
{
int q;
if(p==r)
{
if(ar[r]==x)
{
return r;
}
else
{
return -1;
}
}
else{
q = ((r+p)/2);
if(x<ar[q])
{
return(binarysearch(ar,x,p,q));
}
else
return(binarysearch(ar,x,q+1,r));
}
}
你的代码几乎是正确的。
问题出在状况上,即if(x<ar[q])
.
考虑数组:
int arr[11] = 0 10 20 30 40 50 60 70 80 90 100
其指数为:
0 1 2 3 4 5 6 7 8 9 10
考虑用户传递w=50
,中间索引q
计算为5
条件if(x<ar[q])
将为假,因为 50 不小于 50。 所以它的其他部分,即return(binarysearch(ar,x,q+1,r));
将运行,即return(binarysearch(ar,50,6,10));
这里的代码转错了。我们开始查找错误的子数组。
我们要查找50
项位于第一个子数组中,即0 10 20 30 40 50
,不在第二个子数组中,即60 70 80 90 100
.
修复代码的一种方法是使条件if(x<ar[q])
为if(x<=ar[q])
。或者,您可以添加另一个 if 条件,只检查相等性并根据其他 if 的要求调整 q。
相关文章:
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- 如何在C++中返回向量的从零开始的索引
- 返回向量的单个索引值
- C++函数返回两个 char 数组的相同索引元素
- 访问包含P的有效索引时返回空格的C++字符串
- 当我在网格/面中实现索引时,为什么它会返回OpenGl错误
- 为什么函数的任何索引处的下标运算符在C++中总是返回1
- 如何使用递归函数返回数组中整数的索引?
- "如何使用C++将字符串的第一个和最后一个索引返回到向量中?
- 当索引为 1 时,_BitScanReverse返回 0,这意味着根据 MS "no set bits were found"
- 从给定索引返回子字符字符串的函数
- 如何使用二叉搜索返回姓氏(给定字符串)的第一个索引/出现次数?
- 在索引中插入节点:链接列表未正确返回列表
- 当c 中的矢量容器过载[]运算符时,我对未定义的索引返回什么
- 通过const函数中的参数索引返回std :: map的值
- 数组使用索引返回最大值
- 为什么boost多索引返回错误的迭代器
- C++快速排序索引0返回-842150451