减治法——内插法搜索(Decrease and Conquer by a Factor - Interpolation Search)


内插法搜索(Interpolation Search)
If the elements of a sorted array are distributed reasonably evenly, interpolation search performs better than binary search.

In finding phone number scenario, we’re looking for Shuai. You make an assumption that Shuai’s number is placed in the latter part of your contacts. Go to the most possible place and search. This is the basic idea of Interpolation Search.

We use x-coordinates of a point in a two-dimensional system of cartesian coordinates to represent indexes of an sorted array, and y-coordinates represents the values of elements stored in this array.
这里写图片描述
As all elements are distributed evenly, wen can get some valuable things by using trangle similarity.
这里写图片描述
So,
这里写图片描述
We can use the new m to replace m=[(lo+hi)/2].

算法伪代码(Algorithm Pseudocode)

function InterpolationSearch(A[0..n-1],k)
    lo ⟵ 0
    hi ⟵ n-1
    while lo<=hi do
        m ⟵ (hi-lo)*(K-A[lo])/(A[hi]-A[lo])+lo
        if A[m] = k then
            return m
        if k < A[m] then
            hi ⟵ m - 1
        else
            lo ⟵ m + 1
    return -1

时间复杂度(Time Complexity)
Interpolation search has average-case complexity O(log log n).

Java code

public class Search {

    //Interpolation search method
    public static int InterpolationSearch(int[] A, int k){
        int lo=0,hi=A.length-1,m;
        while(lo <= hi){
            m=(hi-lo)*(k-A[lo])/(A[hi]-A[lo])+lo;
            if(k == A[m]){
                return m;
            }else if(k < A[m]){
                hi = m - 1;
            }else{
                lo = m + 1;
            }
        }
        return -1;
    }

    //Test
    public static void main(String[] args) {
        int[] A={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10};
        int k=4;
        int index = Search.InterpolationSearch(A, k);
        System.out.println("The index is: "+index);
    }
}

运行结果(Result)

The index is: 3

写在最后的话(PS)
Interpolation search is actually an improvement of binary search. The efficiency gets improved a lot.
Welcome questions always and forever.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值