Interpolation search using Java

1. What is interpolation search

Interpolation search, a search method for ordered lists. Interpolation search is a search method based on the comparison between the search key and the largest and smallest record key in the search table. Interpolation search is based on binary search, which improves the selection of search points to adaptive selection and improves search efficiency.

2. Algorithm requirements

  1. The lookup table is an ordered table stored sequentially
  2. The keywords of the data elements are evenly distributed in the lookup table

Third, the search process

Similar to binary search, the difference is that the interpolation search starts from the adaptive selection point

  1. Assuming that the elements in the table are arranged in ascending order, compare the keywords recorded in the middle of the table with the search keywords. If the two are equal, the search is successful;
  2. Otherwise, the middle value plus a certain algorithm position is used to divide the table into two sub-tables. If the key recorded in the middle position is greater than the search key, the previous sub-table is further searched, otherwise the next sub-table is further searched.
  3. Repeat the above process until you find a record that satisfies the condition, so that the search is successful, or until the child table does not exist, and the search is not successful at this time.

Four, code implementation

public class InsertValueSearch {

    public static void main(String[] args) {
        int[] array = new int[100];
        for (int i = 0; i < 100;i++){
            array[i] = i+1;
        }

        int resultIndex = insertValueSearch(array,0,array.length-1,86);
        System.out.println("下标为:"+resultIndex);
    }

    /**
     * @param arrays 有序数组
     * @param left 最小索引
     * @param right 最大索引
     * @param findValue 查找值
     * @return 查找值的下标
     */
    public static int insertValueSearch(int[] arrays,int left,int right,int findValue){
        //判断是否继续进行
        if(left > right || findValue < arrays[0] || findValue > arrays[arrays.length-1]){
            return -1;
        }

        //自适应查找mid
        int mid = left + (right - left) * (findValue - arrays[left]) / (arrays[right] - arrays[left]);
        int midValue = arrays[mid];

        //查找值大于标志值则向右递归查询
        if(findValue > midValue){
            return insertValueSearch(arrays, mid + 1, right, findValue);
        }
        else if(findValue < midValue){
            return insertValueSearch(arrays, left, mid - 1, findValue);
        }
        else{
            return mid;
        }
    }
}

Published 29 original articles · praised 11 · visits 4520

Guess you like

Origin blog.csdn.net/qq_26020387/article/details/105575027