#include <stdio.h>
int bsearch(int a[], int n, int lo, int hi) {
int mid;
mid = (hi + lo) / 2;
if(a[mid] == n)
return 1;
else if(a[mid] > n)
bsearch(a, n, lo, mid);
else
bsearch(a, n, mid, hi);
return 0;
}
int main(void) {
int n, a[7] = {2, 4, 5, 67, 70, 80, 81};
int hi = 6, lo = 0, j;
scanf("%d", &n);
j = bsearch(a, n, lo, hi);
if(j)
printf("Found");
else
printf("Not Found");
return 0;
}
输入:5输出:未找到
有谁能告诉我为什么我得到这个结果?
答案 0 :(得分:1)
您需要修复几个重大问题才能使其正常工作(请参阅以下代码注释中的详细信息)。
将二进制搜索功能更改为以下内容:
int bsearch(int a[], int n, int lo, int hi)
{
// add base case
if (high < low)
return 0; // not found
int mid;
mid=(hi+lo)/2;
if(a[mid]==n)
return 1;
else if(a[mid]>n)
return bsearch(a,n,lo,mid-1); // add return
else
return bsearch(a,n,mid+1,hi); // add return
}
P.S。:根据您在main()
正文中的使用情况,您实际上只需要返回0/1
来指示是否包含值。我建议您使用bool
返回类型以使其更清晰。
答案 1 :(得分:0)
在递归调用中添加“return”,例如:
return bsearch(a,n,lo,mid);
否则,当你在bsearch中返回1时,它不会一直返回到main。
这将使它适用于5.你有其他错误,所以尝试使用许多值并使用IDE和/或printf来查看正在发生的事情。祝你好运,玩得开心!
答案 2 :(得分:0)
这是因为您return 0;
函数中的bsearch
语句总是被执行,因为您只是丢弃递归调用返回的值。在递归函数中,您必须首先确定基本情况。在您的bsearch
中,基本情况应为
low <= hi
这是开始搜索所需值的第一个必须条件的条件。如果未满足此条件,则必须返回false
,即0
。
接下来,返回值函数调用是一个表达式,即它计算为一个值。当您只是调用函数并对结果不执行任何操作时,您将始终使用函数中的最后一个return语句。在这里,我列出了评论中的一些要点以及bsearch
函数中的陈述。
int bsearch(int a[], int n, int lo, int hi) {
// first check for the base condition here
// if(hi < low) return 0;
int mid;
// can cause integer overflow. should be
// mid = lo + (hi - lo) / 2;
mid = (hi + lo) / 2;
if(a[mid] == n)
return 1;
else if(a[mid] > n)
// you are doing nothing with the value returned
// think of the function call as an expression
// return the value of the expression
// should be
// return besearch(a, n, lo, hi);
bsearch(a, n, lo, mid);
else
// same follows here
// should be
// return bsearch(a, n, mid, hi);
bsearch(a, n, mid, hi);
// finally you will always return 0 because this statement is always executed
// all cases have been taken care of.
// no return statement needed here
return 0;
}