【发布时间】:2015-05-17 17:06:43
【问题描述】:
我使用递归调用创建了一个二分搜索程序(忽略 printf 语句)。运行程序后,您会发现它运行良好并获取要找到的元素的索引,但在:
else if (element == arr[mid])
{
printf("\n%d\nmid = %d\nstart = %d\nend = %d\n\n", i, mid,start,end);
return mid;
}
它不返回中间值,而是返回末尾的 0。 (我尝试过 0 以外的值)。
我也尝试在最后返回 mid 而不是返回 0。它总是返回 4。
整个代码是:
#include <stdio.h>
int arr[100]={0,1,2,3,4,5,6,7,8,9}, start=0, end=9, i=0;
int BinaryRecursivSearch(int element, int start, int end)
{
int mid = (start + end)/2;
i++;
printf("\n%d\nmid = %d\nstart = %d\nend = %d\n\n", i, mid,start,end);
if (mid == start)
{
if(element!=end)
{
printf("\nElement not found");
return -1;
}
}
else if (element < arr[mid])
BinaryRecursivSearch(element, start, mid);
else if (element > arr[mid])
BinaryRecursivSearch(element, mid, end);
else if (element == arr[mid])
{
//For the last iteration (or recursion) mid has the correct value in printf
printf("\n%d\nmid = %d\nstart = %d\nend = %d\n\n", i, mid,start,end);
return mid; //It skips this
}
return 0; //It returns this value
}
int main()
{
int element, index;
printf("Enter the element to be searched for: ");
scanf("%d", &element);
index = BinaryRecursivSearch(element, start, end);
printf("\n Element found at %d position", index + 1 );
return 0;
}
【问题讨论】:
-
编译器跳过返回行,你真的不应该责怪编译器,很可能是你的错。
-
请注意,您的最后一个代码块以
else开头,也许这就是它被跳过的原因。我建议您更改两个相同的printf消息之一,以便您知道正在打印哪一个。 -
递归时需要
return BinaryRecursivSearch();。 -
感谢您的快速回复代码到达返回中;我通过更改它上面的 printf 语句来检查它如果你
-
@Prayansh Srivastava 看来您的功能没有任何意义> 有 n0 需要调查它。你应该重写它。
标签: c recursion binary-search