思想:由于二分查找对于大量数据而查找首末位元素时会消耗更多的时间,效率低下。而插值查找便是将查找点选择改为自适应查找。
查找次数与二分法一样
时间复杂度为:O(log2
(log2
n))
将中值设定为 mid=left+(num-arr[left])/(arr[right]-arr[left])*(right-left) //插值公式
JS代码如下
function search (arr, num) {
var index = -1;
var left = 0,
right = arr.length-1;
while (left < right) {
var middle = parseInt(left+(num-arr[left])/(arr[right]-arr[left])*(right-left)); // 此处是插值公式证明见英文文档
console.log(middle)
if (num == arr[middle]) {
index = middle;
return index;
} else if (num > arr[middle]) {
left = middle+1;
} else {
right = middle;
}
}
return index;
}
testing:
var a = [1,2,4,5,7,8,10,11,14,16,19]
console.log(search(a,19))
对于在两端的查值时的确次数减少,效率更快
网友评论