理解神秘工作的递归二进制搜索算法[重复]

问题描述 投票:-1回答:2

在赋值时,我必须使用递归二进制搜索算法输出索引而不是True / False而不修改参数。我度过了一段非常艰难的时期,但在诉诸半试错之后,我偶然发现了这个烂摊子:

#include <iostream>
#include <math.h>
#include <climits>

using namespace std;


int BinarySearch(int arr[], int len, int target) {

    int temp = 0;
    int mid = len/2;

    if (len <= 0) return INT_MIN;  // not found
    if (target == arr[mid]){
        return mid; // found
    }

    if (target < arr[mid]){
        temp = BinarySearch(arr, mid, target);
    }

    else {
        temp = mid+1 + BinarySearch(arr+mid+1, len-mid-1, target);              
    }
}

即使在通过可视化工具运行之后,我也完全不知道它为什么会起作用。它对更改的代码非常敏感,当它无法找到目标时我无法输出-1,所以我至少总是输出一个负数。

我真的不需要它固定,我只是想知道它是如何工作的,因为看起来甚至没有使用递归调用的输出。谢谢。

c++ algorithm c++11 search binary-search
2个回答
5
投票

这是未定义的行为(参见例如Why does flowing off the end of a non-void function without returning a value not produce a compiler error?)。

编译器似乎偶然返回temp,可能是因为它是函数内声明的第一个局部变量。回归温度会解决它。


0
投票

据我所知,你想要返回-1,如果找不到目标,否则返回目标的索引。在

if (len <= 0) return INT_MIN;  // not found

如果找不到目标,你将返回INT_MIN。您需要将其更改为

if (len <= 0) return -1;  // not found

由于您的函数返回int值,因此必须在每个补丁上返回一些内容。您可以通过在函数末尾添加return来修复它:

    if (target < arr[mid]){
        temp = BinarySearch(arr, mid, target);
    }

    else {
        temp = mid+1 + BinarySearch(arr+mid+1, len-mid-1, target);              
    }
    return temp;
}

BinarySearch返回当前target中的arr指数。由于目前的arr通常不以指数0开头,所以你要加上和减去mid+1。如果没有找到目标并且BinarySearch返回-1,你也会这样做。你必须修复else部分:

else {
    int index(BinarySearch(arr+mid+1, len-mid-1, target));
    temp = index == -1 ? -1 : mid + 1 + index;              
}
© www.soinside.com 2019 - 2024. All rights reserved.