【发布时间】: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