c++ - 二进制搜索没有返回正确的值

标签 c++ algorithm binary-search

我正在用 C++ 实现二进制搜索算法,但该算法没有返回正确的值。可以找到代码here .

template<class T>
int binary_search(T search_value, T search_array[]) {

    int mid; /* The middle element of the remaining array to be searched. */
    int min = 0; /* The first index of the array. */
    /* This forumla gives us the size of the array. */
    int max = sizeof(search_array)/sizeof(search_array[0]);

    /* Continue searching until min >= max. */
    while (min < max) {
        /* Compute the value of mid using a formula that won't produce a number
         * larger than the maximum allowed value of an integer. */
        mid = (max-min)/2 + min;

        /* Depending the whether search_value is larger or smaller than the
         * value of whatever is at search_array[mid], set one of mid and max
         * equal to mid. */
        if (search_value > search_array[mid])
            min = mid + 1;
        else if (search_value < search_array[mid])
            max = mid + 1;
        else {
            return mid;
        }
    }

    return -1;
}

给定一个数组 {0, 1, 3, 5, 7, 9} 并搜索 3,该函数应返回 2,即 3 在数组中的索引。不过我的函数返回 -1,这意味着在数组中找不到 3。问题出在哪里?

最佳答案

int max = sizeof(search_array)/sizeof(search_array[0]);

这种方法不适用于计算数组的大小,它只适用于创建数组的函数。

将数组的大小作为函数的参数传递,这是最简单的方法。

关于c++ - 二进制搜索没有返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9268623/

相关文章:

c++ - 返回类(class)成员是一种不好的做法吗?

C++ 文件 I/O——不能同时读/写?

c - 在 C 中搜索数据结构数组的成员

c++ - 警告 : cast from pointer to integer of different size [-Wxpointer-to-int-cast]

algorithm - 数组的实时排序

algorithm - 如果使用正态分布的目标值进行训练,非线性回归算法会表现得更好吗?

c - Hackerrank 挑战超时

big-o - 递归函数的渐近复杂度是如何推导的

C++二进制搜索以查找不动点的索引

c++ - 交叉编译找不到引用