繁体   English   中英

这是一个二进制搜索代码,我无法找出问题所在

[英]it is a binary search code and i m not able to figure out the problem

这是我的代码。代码正在运行,但没有得到正确的结果。 例如,在程序中搜索 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;
}

这是问题所在:

if(item==arr[mid])
        return mid;
     else if(item<arr[mid])
        low=mid+1;
     else
        up=mid-1;

只需根据中索引arr[mid]的值更改选择low索引和up索引的条件,例如:

 if(item==arr[mid])
    return mid;
 else if(item<arr[mid])
    up=mid-1;
 else
    low=mid+1;

或将此条件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;

注意: while(low<=up && item!=arr[mid])在这一行中,您在arr[mid]使用mid ,然后才为其分配值,从而导致未定义行为。 (此外,while 测试的&& item!=arr[mid]部分是不必要的。)信用:1201ProgramAlarm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM