【问题标题】:Computing mid in Interpolation Search?在插值搜索中计算中间值?
【发布时间】:2015-11-26 14:32:31
【问题描述】:

我知道插值搜索是对二分搜索的修改,在二分搜索中,输入在每次迭代中通过计算分成相等的两半

mid = (low + high) / 2

在插值搜索中,中间值计算为

mid = low + (key - arr[low]) * ((high - low) / (arr[high] - arr[low]))

现在我需要了解插值搜索中计算mid的公式。

参考:https://en.wikipedia.org/wiki/Interpolation_search#Sample_implementation

【问题讨论】:

  • 假设low = 10high = 20arr[low] == 100arr[high] == 200。现在为key == 110key == 150key == 190 计算mid
  • @Henrik 但是这个公式是如何推导出来的?

标签: algorithm search


【解决方案1】:

您可以将数组arr 视为一个函数f,它作用于索引并返回一个值,该值是单调的(因为数组已排序)。所以你有你的初始数据f(low) = mf(high) = M。现在你可以用一条直线插入你的函数f,这是很合理的,因为你的f是单调的,你只有2个点。 所以你的插值应该是通过抛出点(low, m)(high, M) 的线(线性函数)。这是它的方程式

(y - f(low))/(f(high) - f(low)) = (x - low)/(high - low)

所以y 这里是搜索空间的元素,x 来自域(x 是数组的索引)。因此,如果您的函数 f 与它的插值相同,那么您的 key 的索引将是:

x = low + (high - low)*(key - f(low))/(f(high) - f(low))

因此,假设您的函数 f 接近于它的插值,您应该只检查 x 处的值 f 以查看它是否是目标。否则,您只需缩小插值间隔。

【讨论】:

【解决方案2】:

@JustAnotherCurious 答案的扩展

他提出的等式是基于Interpolation Formula(一行的等式)

现在,将f() 视为接受索引并返回其y 轴值的函数,

y1 = f(low)
y2 = f(high)
x1 = low
x2 = high

(y - f(low)) = [(f(high) - f(low)) / (high - low)] * (x - low);

OR

x = low + [(high - low) * (y - f(low))] / (f(high) - f(low))

here: y = key
we are looking for position(value) of x.

【讨论】:

    猜你喜欢
    • 2011-10-07
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多