二进制搜索没有给出正确的输出
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
> 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);
}
这是正确的代码
#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);
}
Getting wrong output of -1 and -1 it is going in the else section no compile time errors getting an output of -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);
}
这是正确的代码
#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);
}