33

查找--插值查找(Java)

 3 years ago
source link: https://segmentfault.com/a/1190000023059396
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

查找--插值查找(Java)

博客说明

文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!

介绍

插值查找算法类似于二分查找,不同的是插值查找每次从自适应mid处开始查找。

自适应

计算自适应mid

int mid = left + (right – left) * (findVal – arr[left]) / (arr[right] – arr[left])

代码

package cn.guizimo.search;

public class InsertValueSearch {
    public static void main(String[] args) {
        int max = 100;
        int[] arr = new int[max];
        for (int i = 0; i < max; i++) {
            arr[i] = i + 1;
        }
        int index = insertValueSearch(arr, 0, arr.length - 1, 100);
        if(index == -1){
            System.out.println("未找到");
        }else {
            System.out.println("下标为:"+index);
        }
    }

    public static int insertValueSearch(int[] arr, int left, int right, int value) {
        if (left > right || value < arr[0] || value > arr[arr.length - 1]) {
            return -1;
        }
        int mid = left + (right - left) * (value - arr[left]) / (arr[right] - arr[left]);
        int midValue = arr[left];
        if (value > arr[mid]) {
            return insertValueSearch(arr, mid + 1, right, value);
        } else if (value < arr[mid]) {
            return insertValueSearch(arr, left, mid - 1, value);
        } else {
            return mid;
        }
    }
}

注意的事项

  • 对于数据量较大,关键字分布比较均匀的查找表来说,采用插值查找, 速度较快.
  • 关键字分布不均匀的情况下,该方法不一定比折半查找要好

感谢

尚硅谷

万能的网络

以及勤劳的自己


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK