二进制搜索没有提供正确的输出

时间:2017-01-30 17:40:37

标签: c algorithm binary-search

  

获取-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);
}

1 个答案:

答案 0 :(得分:0)

这是一个正确的代码

#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);
}