【问题标题】:Binary Search doesn't give correct output二分搜索没有给出正确的输出
【发布时间】:2017-01-31 02:13:10
【问题描述】:

得到 -1 和 -1 的错误输出,它在 else 部分没有编译时错误得到 -1 的输出

> Here the code is going out of the loop for all test cases how?I am unable to understand what is the mistake as I am new to programming

请帮助我,我在线性搜索中问过一个非常相似的问题 这是尝试过的迭代方法 使用递归不起作用。

int bin_search(int A[], int left, int right, int k)
{
    int found=0,mid;
    mid=(left+right)/2;
    if(right>=1)
    {
        if(k>A[left])
        {
            left=k;
            bin_search(A,mid+1,right,k);
        }
        else if(k<A[right])
        {
            right=k;
            bin_search(A,left,mid-1,k);
        }
        else if(A[mid]=k)
        {   
            return mid;
        }   

    }
   else return -1;
}
int main()
{int n;
 int A[]={1,2,3,4,5};
 int a=bin_search(A,0,n-1,4);
 printf("%d ",a);
}

【问题讨论】:

  • 您应该真的花点时间尝试使用一致的格式。这看起来很可怕。
  • 阅读编译器警告。 (如果您没有收到编译器警告,请打开编译器警告。)
  • 请格式化叙述和代码。我们将花费与您提出的问题一样多的时间来回答这个问题。
  • 澄清一下,这个问题将按照目前的状态关闭。
  • 对您的代码应用适当的缩进。很难阅读。

标签: c algorithm binary-search


【解决方案1】:

这是正确的代码

#include <iostream>
using namespace std;

int bin_search(int A[], int left, int right, int k)
   {
      int found=0,mid;
      mid=(left+right)/2;
      if(left <= right)
      {
         if(k>A[mid])
         {
            left=mid+1;
            bin_search(A,mid+1,right,k);
         }
         else if(k<A[mid])
         {
            right=mid-1;
            bin_search(A,left,mid-1,k);
         }
        else if(A[mid]=k)
        {   
            return mid;
        }   

     }
     else return -1;
}
int main()
{      int n = 5;
       int A[]={1,2,3,4,5};
       int a=bin_search(A,0,n-1,2);
       printf("%d ",a);
}

【讨论】:

  • 对不起,你的代码给出了完全相同的错误输出,我得到的输出是 -1 在这种情况下。
  • 用数组的sizeof初始化n=sizeof(arr)/sizeof(arr[0]);
  • 为什么在 c 问题中使用 c++ 答案? c++ 标签在您回答前 15 分钟被删除。
  • 运行代码 sn-p 抛出错误,但我假设是因为您为 printf 使用了错误的头文件 ,我明白您的意思非常感谢!!
  • 这段代码存在整数溢出错误:mid=(left+right)/2可以在左右足够大时溢出。您可以通过重写表达式来防止这种情况,例如left + (right - left) / 2。这是实现排序算法时最典型的错误之一。这是不重新实现成熟库可用的算法的原因之一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多