提高此搜索的性能
Improving the performance of this search?
有没有办法使用更快的方法进行以下搜索?A 数组上的项目按 DESC 顺序排序。
int find_pos(int A[], int value, int items_no, bool only_exact_match)
{
for(int i = 0; i < items_no; i++)
if(value == A[i] || (value > A[i] && !only_exact_match))
return i;
return -1;
}
您可以在您的情况下使用std::lower_bound
算法。正如其他人所写的那样,它使用 O(log N) 执行二进制搜索。它将是这样的:
int find_pos(int A[], int value, int items_no, bool only_exact_match)
{
const int *pos_ptr = std::lower_bound(A, A + items_no, value, std::greater<int>());
const ptrdiff_t pos = pos_ptr - A;
if (pos >= items_no)
return -1;
if (*pos_ptr != value && only_exact_match)
return -1;
return pos;
}
二叉搜索
int left = 0;
int right = items_no; // Exclusive
while (left < right) {
int mid = (left + right) / 2;
if (value == A[mid])
return mid;
if (value < A[mid]) {
left = mid + 1;
} else {
right = mid;
}
}
return only_exact_match ? -1 : right - 1; // The greater
由于数组已排序,因此可以按步骤进行搜索,类似于平分法。首先,对照您的值检查中点。如果相等,你就有了答案。如果它更大,则您的值位于数组的下半部分。如果没有,您的值在上半部分。通过平分数组的其余元素来重复此过程,直到找到您的值或用完元素。至于你的第二个 if 子句,如果没有找到匹配的值,最接近的较小元素是元素 i+1,如果存在的话(即你不在数组的末尾)。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 有根的二进制搜索树.保留与其父级的链接
- OpenMP阵列性能较差
- 递归列出所有目录中的C++与Python与Ruby的性能
- 在C++中搜索嵌套多映射值
- 大小相等但成员数量不同的结构之间的性能差异
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 为什么constexpr的性能比正常表达式差
- 正在尝试重载二进制搜索树分配运算符
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 向量上的线性搜索
- 使用 TinyXPath 搜索 XPath 时出现性能问题
- 性能问题C++ - 搜索数组
- 随机生成的排序数组:搜索性能比较
- 过滤字符串过长会影响ldap的搜索性能吗?
- 复杂性理论-二进制搜索是否具有deque C++数据结构的对数性能
- C++搜索性能
- 提高此搜索的性能