减治法——内插法搜索(Decrease and Conquer by a Factor

来源:互联网 发布:最可靠的单片机 编辑:程序博客网 时间:2024/05/22 11:51

内插法搜索(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.

原创粉丝点击