【发布时间】:2017-08-12 00:21:06
【问题描述】:
我已经在 C 中实现了二进制搜索的初学者递归版本。但是,当要找到的元素位于数组的最后位置时,它似乎不起作用。有没有办法在不改变函数原型的情况下解决这个问题?
#include <stdio.h>
int search(int value, int values[], int n);
int main() {
int a[] = { 26, 27, 28 };
if (search(28, a, 3) == 0)
printf("Found.\n");
else
printf("Not found.\n");
}
int search(int value, int values[], int n)
{
if (n <= 0)
return 1;
if (value < values[n/2])
// Search the left half
return search(value, values, n/2);
else if (value > values[n/2])
// Search the right half, excluding the middle term
return search(value, values + n/2 + 1, n/2 - 1);
else
return 0;
return 1;
}
【问题讨论】:
-
我刚刚运行了你的代码;它工作正常吗?你能澄清你的错误,你的可重现步骤吗?
-
如果
value == values[n/2],你为什么要返回0?你不应该返回n/2吗?而return 1行也没用。 -
如果 N 为 3,你认为
n/2 - 1会是什么? -
n/2 - 1-->n - n/2 - 1
标签: c arrays binary-search