提高此搜索的性能

Improving the performance of this search?

本文关键字:性能 搜索 高此      更新时间:2023-10-16

有没有办法使用更快的方法进行以下搜索?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,如果存在的话(即你不在数组的末尾)。