//内插搜索
function interpolationSearch(array, value) {
const { length } = array
let low = 0
let high = length - 1
let position = -1
let delta = -1
while (low <= high && value >= array[low] && value <= array[high]) {
delta = (value - array[low]) / (array[high] - array[low])
position = low + Math.floor((high - low) * delta) //内插计算公式 查找的初始位置
if (array[position] === value) {
return position
}
if (array[position] < value) {
low = position + 1
} else {
high = position - 1
}
}
return 'NOT_EXIST'
}
console.log(interpolationSearch([1, 2, 3, 4, 5], 2));
内插搜索算法js实现
最新推荐文章于 2022-08-25 20:12:21 发布