二叉搜索功能始终返回 -1 值而不是索引

binary search fuction always returns -1 value instead of index

本文关键字:索引 返回 搜索 功能      更新时间:2023-10-16

我的二进制搜索函数总是返回 -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。