我正在阅读一本《数据 struct 和算法》一书,在关于数组内插搜索的章节中,这本书包括了这段代码:
def interpolation_search(ar:list, lo:int, hi:int, x:int):
if (lo <= hi and x >= ar[lo] and x <= ar[hi]):
pos = lo + ((hi - lo) // (ar[hi] - ar[lo]) * (x - ar[lo]))
print(pos)
if ar[pos] == x:
return pos
if ar[pos] < x:
return interpolation_search(ar, pos + 1, hi, x)
if ar[pos] > x:
return interpolation_search(ar, lo, pos - 1, x)
return -1
if __name__ == '__main__':
v = 18
ar = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47]
assert(interpolation_search(ar, 0, len(ar)-1, v) == 4)
现在我的问题是,如果我运行它,它将打印0、1、2、3、4(从打印(Pos)) 这看起来像是一个更复杂的线性搜索.
那么我错过了什么,或者这个代码是错误的?
我期望这个插值搜索根据公式的逻辑将数组分成两个,但似乎公式的输出总是i,i+1,i+2,.