二进制搜索未返回正确的值

mau*_*add 0 c++ algorithm binary-search

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

Man*_*lio 5

int max = sizeof(search_array)/sizeof(search_array[0]);
Run Code Online (Sandbox Code Playgroud)

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

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

  • 问题是你的函数中的`search_array`只是一个指向内存地址的指针,而不是一个数组,因此除了你创建数组的函数(在本例中是main)之外,这种方法不起作用.没有标准的方法来计算数组的大小,但常见的方法是将其作为函数的参数传递.其他方法可能包括使用特定结构,如`std :: vector`,它存储数组的长度并消除在运行时计算它的问题. (3认同)