python - 二进制搜索 : weird middle point calculation

标签 python algorithm search

关于列表中点的计算:为什么会有

i = (first +last) //2 

last被初始化为len(a_list) - 1?从我的快速测试来看,这个算法没有 -1 可以正常工作。

def binary_search(a_list, item):
    """Performs iterative binary search to find the position of an integer in a given, sorted, list.
    a_list -- sorted list of integers
    item -- integer you are searching for the position of
    """

    first = 0
    last = len(a_list) - 1

    while first <= last:
        i = (first + last) / 2

        if a_list[i] == item:
            return '{item} found at position {i}'.format(item=item, i=i)
        elif a_list[i] > item:
            last = i - 1
        elif a_list[i] < item:
            first = i + 1
        else:
            return '{item} not found in the list'.format(item=item)

最佳答案

最后一个合法索引 len(a_list) - 1。该算法 正常工作,因为first 将始终不超过此值,因此截断均值永远不会超出范围。但是,如果没有 -1,大约一半的时间中点计算将比最佳值大 1,导致速度略有下降。

关于python - 二进制搜索 : weird middle point calculation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48572552/

相关文章:

python - 如何使用 Python 的 CSV DictReader 解析 CSV 输出?

python - 为什么这个主要测试有效?

javascript - 在更长的数字中查找序列的算法

database - 使用索引在数据库中进行不区分大小写的搜索?

javascript - 在隐藏的 div 中快速查找 (ctrl+f)

git - 在 GitHub 上搜索具有特定框架和演示的项目

python - Python3 中的 numpy genfromtxt 问题

php - 从 Python/AppEngine 迁移到 PHP 的最佳框架

python - Scikit Learn 逻辑回归中预测的逆是正确的

c - 用于嵌入式系统的 C 中最快的数组查找算法?