[英]it is a binary search code and i m not able to figure out the problem
Here is my code.The code is running but not getting the right results.这是我的代码。代码正在运行,但没有得到正确的结果。 For ex- searching 3 in the program is getting output "not found" even though present.
例如,在程序中搜索 3 会得到输出“未找到”,即使存在。
#include<stdlib.h>
#include<iostream>
using namespace std;
int Bsearch(int arr[],int item,int n)
{
int low,mid,up;
low=0;up=n-1;
while(low<=up && item!=arr[mid])
{
mid=(low+up)/2;
if(item==arr[mid])
return mid;
else if(item<arr[mid])
low=mid+1;
else
up=mid-1;
}
return -1;
}
int main()
{
int index,item;;
int arr[]={1,2,3,4,5,6,7,8,9};
cout<<"enter search item\n";
cin>>item;
index=Bsearch(arr,item,9);
if(index!=-1)
cout<<"element found at position"<<(index+1);
else
cout<<"element not found";
return 0;
}
Here is the problem:这是问题所在:
if(item==arr[mid])
return mid;
else if(item<arr[mid])
low=mid+1;
else
up=mid-1;
just change the conditon of choosing low
and up
index according the value of mid index arr[mid]
like:只需根据中索引
arr[mid]
的值更改选择low
索引和up
索引的条件,例如:
if(item==arr[mid])
return mid;
else if(item<arr[mid])
up=mid-1;
else
low=mid+1;
OR change this condition else if(item<arr[mid])
into else if(item > arr[mid])
and your code will work fine.或将此条件
else if(item<arr[mid])
更改为else if(item > arr[mid])
并且您的代码将正常工作。
if(item==arr[mid])
return mid;
else if(item > arr[mid])
low=mid+1;
else
up=mid-1;
NB: while(low<=up && item!=arr[mid])
in this line, you're using mid
in arr[mid]
before it has been assigned a value, resulting in Undefined Behavior.注意:
while(low<=up && item!=arr[mid])
在这一行中,您在arr[mid]
使用mid
,然后才为其分配值,从而导致未定义行为。 (Also, the && item!=arr[mid]
part of the while test is unnecessary.) Credit: 1201ProgramAlarm (此外,while 测试的
&& item!=arr[mid]
部分是不必要的。)信用:1201ProgramAlarm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.