插值查找

算法描述

插值查找是二分查找的优化
适用条件:数据量大,待查找的数组是均匀分布的
下面是python代码

def insertValuesearch(a,targetValue):
    left = 0
    right = len(a)-1
    if targetValue>a[right] or targetValue<a[left]:
        return "{} not find".format(targetValue)
    # 循环条件
    while left < right:
        # 插值查找的公式
        mid = left +abs(int((right-left)*((targetValue-a[left])/(a[right]-a[left]))))
        # 当前值小于查找值,在右边查找
        if a[mid] < targetValue:
            left = mid + 1
        elif a[mid] > targetValue:
            right = mid - 1
        else:
            return "index of {} is {}".format(targetValue,mid)
    return "{} not find".format(targetValue)```
posted @ 2021-04-06 10:44  inss!w!  阅读(56)  评论(0编辑  收藏  举报