python:插值查找法

插值查找本质是二分查找,插值查找对二分查找算法中查找中间位置的计算逻辑进行了改进。
插值查找基于二分查找算法,主要将查找点的选择改进为自适应选择;当然,差值查找也属于有序查找。

二分法:

mid_idx = (r_ldx + l_idx) // 2

插值法:

mid_idx = l_idx + (target - nums[l_idx]) // (nums[r_idx] - nums[l_idx]) * (r_idx - l_idx)

代码实现:

def interpolation_search(v_list, target):
    """
    Interpolation search algorithm to find the index of a number in the given v_listay.
    """
    n = len(v_list)
    left = 0
    right = n - 1
    time = 0
    mid_idx = 0

    if target < v_list[0] :
        return False, 1, 0
    elif target > v_list[n - 1]:
        return False, 1, n - 1

    while left <= right and target >= v_list[left] and target <= v_list[right]:
        mid_idx = left + ((target - v_list[left]) * (right - left)) // (v_list[right] - v_list[left])
        time += 1
        if v_list[mid_idx] == target:
            return True, time, mid_idx
        elif v_list[mid_idx] < target:
            left = mid_idx + 1
        else:
            right = mid_idx - 1

    return False, time, mid_idx

vv_list = [10,22, 30, 35, 40, 45,46,47, 48, 49]
targett = 50
flag, times, mid_idx = interpolation_search(vv_list, targett)
if flag :
    print(f"Element {targett} is present at index {mid_idx},search times :{times}")
else:
    print(f"Element {targett} is not present in v_list,better at index {mid_idx} and value is {vv_list[mid_idx]},search times :{times}")

输出:

Element 50 is not present in v_list,better at index 9 and value is 49,search times :1

你可能感兴趣的:(深度学习与Python,python,二分法,插值法,查找算法,有序查找)