【问题标题】:it is a binary search code and i m not able to figure out the problem这是一个二进制搜索代码,我无法找出问题所在
【发布时间】:2020-10-19 18:42:52
【问题描述】:

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

【问题讨论】:

  • 您是否尝试过使用调试器或进行一些打印以查看发生了什么?本网站并非真正旨在帮助您查找您的错误。
  • 您还在使用 mid 之前为其分配了一个值,从而导致未定义的行为。 (另外,while 测试的 &amp;&amp; item!=arr[mid] 部分是不必要的。)
  • @1201ProgramAlarm 没错!

标签: c++ c++11


【解决方案1】:

问题来了:

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

只需根据中间索引arr[mid]的值改变选择lowup索引的条件,比如:

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

或者将此条件 else if(item&lt;arr[mid]) 更改为 else if(item &gt; arr[mid]),您的代码将正常工作。

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

N.B:while(low&lt;=up &amp;&amp; item!=arr[mid]) 在这一行中,您在 arr[mid] 中使用 mid 在它被分配一个值之前,导致未定义的行为。 (另外,while 测试的 &amp;&amp; item!=arr[mid] 部分是不必要的。)Credit: 1201ProgramAlarm

【讨论】:

    猜你喜欢
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2014-12-30
    • 2011-09-16
    相关资源
    最近更新 更多