为什么不能在以下数组上使用二叉搜索

Why can’t you use the binary search on the following array?

本文关键字:搜索 数组 不能 为什么      更新时间:2023-10-16

为什么你不能在这个数组上使用二叉搜索?
int A[10] = {4, 5, 6, 2, 8, 1, -1, 17};

在计算机科学中,二叉搜索,也称为半区间搜索、对数搜索或二进制斩波,是一种搜索算法,用于查找排序数组中目标值的位置。维基百科您使用的数组未排序,因此二叉搜索不起作用。

首先你需要使用任何排序机制对它进行排序

Binary search需要一个排序的元素集合。例如,如果使用 C++11 或更高版本,则可以轻松对其进行排序:

std::sort(std::begin(A), std::end(A)); // requires #include <algorithm>

要进行二进制搜索,首先您必须对数组进行排序。

您可以在此处找到文档和示例

这是另一个例子:

#include <algorithm>    // std::binary_search, std::sort
#include <vector>       // std::vector
int main() {
    int A[10] = {4, 5, 6, 2, 8, 1, -1, 17};
    std::vector<int> v(std::begin(A), std::end(A));
    std::sort (v.begin(), v.end());
    int n = 2;
    // now you can use binary search
    bool foundN = std::binary_search (v.begin(), v.end(), n);
}