简体   繁体   English

二分搜索没有给出正确的输出

[英]Binary Search doesn't give correct output

Getting wrong output of -1 and -1 it is going in the else section no compile time errors getting an output of -1得到 -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

please help me I had asked a pretty similar question in linear search This is iterative approach tried even with recursive doesn't work.请帮帮我我在线性搜索中问了一个非常相似的问题这是即使使用递归也尝试过的迭代方法不起作用。

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

Here's a correct code这是正确的代码

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

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

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