为什么不能在以下数组上使用二叉搜索
Why can’t you use the binary search on the following array?
为什么你不能在这个数组上使用二叉搜索?
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);
}
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 如何在动态数组上使用搜索函数
- 在 C++ 中搜索动态分配的数组中的出现次数
- 当您在此单词中搜索单词时调整字符数组的大小?
- 在对象数组中搜索字符串并返回相应值的函数
- C++线性搜索算法,确定数组中元素的数量
- 递归二进制搜索与字符串数组
- 运行搜索数组
- 比较/搜索数组中多个整数的最佳解决方案
- C 搜索数组以获取一个数字,但如果找不到该数组,则不会触发其他语句
- 更高效的是,每次都读取文件或搜索数组中的数据
- 二叉搜索数组溢出 C++
- 在c++中搜索数组中的素数
- 性能问题C++ - 搜索数组
- C++搜索数组中最大的数字
- 我需要帮助创建一个可以搜索数组的函数
- 我想要一个递归函数来检查使用二进制搜索数组的顺序
- c#到c++的转换:搜索数组
- 搜索数组以查找单词的单独实例
- 搜索数组并比较它们