C#算法设计查找篇之03-插值查找

版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/81844909

插值查找(Interpolation Search)

插值查找是二分查找的更高效版本,它不会每次按2平分原问题规模,而是应用一个技巧来尽快的接近目标关键字。


示例: 

public class Program {

    public static void Main(string[] args) {
        int[] array = { 8, 11, 21, 28, 32, 43, 48, 56, 69, 72, 80, 94 };

        Console.WriteLine(InterpolationSearch(array, 80, 0, array.Length - 1));

        Console.ReadKey();
    }

    private static int InterpolationSearch(int[] array, int key, int low, int high) {
        if (low > high) return -1;
        var mid = (int)(low + ((double)key - array[low]) / 
            (array[high] - array[low]) * (high - low));
        if (array[mid] == key)
            return mid;
        else if (array[mid] > key)
            return InterpolationSearch(array, key, low, mid - 1);
        else
            return InterpolationSearch(array, key, mid + 1, high);
    }

}

请注意以上递归实现为尾递归,详情参考我的另一篇博文:

C#开发笔记之06-为什么要尽可能的使用尾递归,编译器会为它做优化吗?

以上是插值查找算法的一种实现,以下是这个案例的输出结果:

10

分析:

在最坏的情况下插值查找的时间复杂度为: O(log(logn)) 。

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/81844909