python - Python中反向排序列表的二进制搜索

标签 python binary-search

如果列表按升序排序,已经有一个关于如何使用 bisect 模块在 Python 中进行二进制搜索的主题:Binary search (bisection) in Python

有没有一种对倒序排列的列表进行二分查找的好方法?

最佳答案

这就是documentations说:

Unlike the sorted() function, it does not make sense for the bisect() functions to have key or reversed arguments because that would lead to an inefficient design (successive calls to bisect functions would not “remember” all of the previous key lookups).

所以不支持自定义顺序。任何绕过它的尝试(例如将列表反转两次,或准备一个单独的键列表)都将花费线性时间,这完全破坏了二分搜索的点,它是对数的。

这是一个接受比较器的二分查找的实现

def bisect(arr, val, cmp):
    l = -1
    r = len(arr)
    while r - l > 1:
        e = (l + r) >> 1
        if cmp(arr[e], val): l = e
        else: r = e
    return r

它的行为类似于bisect_right,如果您需要bisect_left,请在最后返回l。以下是反向数组的示例用法:

>>> a = [10**8 - x for x in range(10**8)]
>>> bisect(a, 100, lambda x, y: x > y)
99999900

关于python - Python中反向排序列表的二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29045162/

相关文章:

python - 检查转义字符的 python 字符串

python - 二元选择过程

java - 如何通过二进制搜索搜索 ArrayList 中的任何值

xml - 以类似 SAX 的方式从磁盘二进制搜索 XML - 明智吗?可能的?

python - Mod_Wsgi PythonHome 不工作

python - 为字典中的一个键附加多个值

python - 为什么tempfile和os.chdir()抛出RecursionError?

c++ - C++ lower_bound()搜索最接近目标值的元素

c++ - 二进制搜索插入字符字符串。错误在哪里?

python - 我如何训练一个系统来识别 Python 中的模式?