c++ - 如何找到二分查找算法的迭代次数?

标签 c++ algorithm c++11 binary-search

如何获取二分查找的迭代次数?

这是我的代码:

int main() 
{
    int target = 11;
    int N = 10;
    std::vector<int> index;
    int num;

    for (int i = 0; i < N; i++) {
        index.push_back(i);
    }

    int counter = 0;
    unsigned int M, L = (unsigned int)-1, R = N;

    M = (R - L) / 2;  // Assume N is not zero

    do {
        int value;
        M = M + L;
        value = index[M];
        if (value < target) L = M; else R = M;
        M = (R - L) / 2;
        counter++;
    } while (M);  // M is the size of the current interval

    std::cout << R << '\n';
    std::cout << "counter: " << counter << '\n';

    system("pause");

    return 0;
}

我想知道迭代次数取决于 N。 我知道这个算法是如何工作的,但我想要迭代次数 用数学表示。

最佳答案

我会通过使用递归二进制搜索函数来递归递增。 在二进制检查的每个分支中,只需递增 1 即可递归计算迭代次数。

See live here

#include <iostream>
#include <vector>

std::size_t binarySearch(
    const std::vector<int>& arr,        // pass array as non-modifiyable(const ref)
    std::size_t start, std::size_t end, // start and end indexes of the array
    const int target)                   // target to find
{
    if (arr.size() == 1) return arr[0] == target ? 1 : 0; // edge case

    if (start <= end)
    {
        const std::size_t mid_index = start + ((end - start) / 2);
        return arr[mid_index] == target ? 1 :                         // found the middle element
               arr[mid_index] < target ?
                 binarySearch(arr, mid_index + 1, end, target) + 1:   // target is greater than mid-element
                 binarySearch(arr, start, mid_index - 1, target) + 1; // target is less than mid-element
    }
    return 0;
}

int main()
{
    int target = 11;
    const int N = 10;
    std::vector<int> index;
    index.reserve(N); // reserve some memory
    for (int i = 0; i < N; i++) {
        index.push_back(i);
    }
    std::cout << "counter: " << binarySearch(index, 0, index.size() - 1, target) << std::endl;
    return 0;
}

输出:

counter: 4

关于c++ - 如何找到二分查找算法的迭代次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55987012/

相关文章:

c++ - 连续 cin 的问题

algorithm - 使用 map reduce 使用 bfs 遍历图形的有效方法是什么?

在 C++ 应用程序后面运行的 C++ 计时器

c++ - 类模板的可视方法何时实例化?

c++ - 无法在 Mingw-w64 中使用 "uniform_int_distribution",但 "exponential_distribution"可以使用

c++ - std::mutex 是否足以使所有先前的读写发生在同一线程中的后续读写之前?

使用非类型模板参数的 C++ 优化

c++ - 使用具有相同条件变量的不同互斥体是否有意义?

algorithm - 用于文本聚类的 k-means

algorithm - 按用户评论标准订购对象