"价格-是右"二分搜索

时间:2015-08-09 10:00:17

标签: python algorithm binary-search

我需要编写一个函数来查找给定动画时间轴上的时间点的动画帧。我最后写的是我只能描述为'#34;价格合适"二分搜索:二进制搜索,在有序列表中找到最接近的值而不会过去。

例如,如果时间是42,我想在给定以下list帧时间的情况下找到要提取的帧的索引:

times = [0, 1, 2, 3, 4, 5, 6, 41, 43]   # assumed to be sorted

在这种情况下,它会返回索引7,因为41是最接近42目标时间的时间。我的算法如下:

def binary_search(t, start, end):
    if start == end:
        return start

    if end - start == 1:
        if t < times[end]:
            return start
        else:
            return end

    i = start + ((end - start) / 2)

    if times[i] > t:
        return binary_search(t, start, i)
    elif times[i] < t:
        return binary_search(t, i, end)
    else:
        return i

它并不完全忠于价格是正确的,因为低于最低元素的价值仍然可以“赢得”#34; (例如。-1将返回索引0)。

所以,这一切都有效并且很好。但是我想知道这个算法是否有特定的名称?

ideone here

0 个答案:

没有答案