【问题标题】:Recursive binary search returns correct target, but at the middle index in array递归二分搜索返回正确的目标,但在数组的中间索引处
【发布时间】:2020-06-26 23:40:44
【问题描述】:

尝试递归二进制搜索算法,它返回我通过它但在错误索引处的正确目标。

索引似乎总是高值和低值的中心索引。

我在 binarySearch 的 if 语句中添加了一些 printf,它接缝它从不递归调用自身,总是返回中间值。

即使您将目标更改为数组中未保存的值,它也会返回索引 5 和正确的目标值。

int main(void)
{
    int const numbers[10] = {1,3,4,7,13, 14, 17, 18, 20, 23};
    int const target = 20;
    int result = 0;
    result = binarySearch(&numbers, 0, 10, target);
    if (result != -1)
    {
        printf("Element is found in array in index: %d, and holds value: %d\n", result + 1, numbers[result]);
    }
    else
    {
        printf("Element is not found in array\n");
    }
}

int binarySearch(int* arr, int low, int high, int x)
{
    if (high >= low)
    {
        int mid = low + (high - low) / 2;
        if (arr[mid] = x)
        {
            printf("mid\n");
            return mid;
        }
        else if (arr[mid] > x)
        {
            printf("high\n");
            return binarySearch(arr, low, mid - 1, x);
        }
        else if (arr[mid] < x)
        {
            printf("low\n");
            return binarySearch(arr, mid + 1 , high, x);
        }   
    }
    else
    {
        return -1;
    }
}

输出

Element is found in array in index: 5, and holds a value of: 20

想法?

【问题讨论】:

  • 你的编译器没有抱怨 if (arr[mid] = x) 吗?你是说== 吗?
  • 在我大学提供的 Linux 服务器上编译,使用 Visual Studio 2019 进行编辑。没有收到任何警告,但这样做解决了我的问题。您是否更了解为什么这会解决? (对 C 还是新手,并努力精通它)
  • 就C而言,赋值是一个表达式,其值是赋值的结果。所以在if (arr[mid] = x)中,x被赋值给arr[mid],表达式的结果就是arr[mid]的新值,即本例中的20,就C而言是true被关注到。另一方面,对于==,如果两边的值相等,则表达式返回1。这是 C 中的标准 gotcha。FWIW,通过递归进行二进制切割有点奇怪——循环就可以完成这项工作。
  • 另外:我认为binarySearch() 的初始调用应该是0, 9 而不是1, 10——C 数组是0 的来源。您需要仔细考虑lowhighbinarySearch() 中所指的内容。
  • 到一个点...sizeof(numbers) 将为您提供以 bytes 为单位的数组大小,在这种情况下,可能为 40。sizeof(numbers)/sizeof(numbers[0]) 将为您提供元素数组的大小,在本例中为 10。注意这是分配的大小,而不是静态初始化 { 1, 3, ... } 中的元素数。我会将binarySearch() 更改为采用const int* arr参数——这将与const numbers[] 参数保持一致。

标签: c algorithm recursion search binary


【解决方案1】:

简单的错误

就 C 而言,arr[mid] = x 是赋值,而不是比较。

由于x 不返回0,if 语句被清除并返回错误的索引,但返回正确的值。 如果我们将目标更改为 0,则 if 语句返回 false,并且不返回中间索引。

我们需要将 arr[mid] = x 更改为 arr[mid] == x 以将其从分配更改为比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 2017-02-14
    • 2013-06-04
    • 1970-01-01
    • 2014-01-07
    相关资源
    最近更新 更多