Algorithm 为什么这种算法适用于二次探测?
为什么将偏移量增加2是有意义的?我知道这个算法是有效的,我已经将结果绘制成x^2类型的图形,但我就是看不到。有人能简单地解释一下吗?谢谢大家!Algorithm 为什么这种算法适用于二次探测?,algorithm,math,hash,hashtable,quadratic-probing,Algorithm,Math,Hash,Hashtable,Quadratic Probing,为什么将偏移量增加2是有意义的?我知道这个算法是有效的,我已经将结果绘制成x^2类型的图形,但我就是看不到。有人能简单地解释一下吗?谢谢大家! size_t FindPos(const HashedObj & x) const { size_t offset = 1; size_t current_pos = InternalHash(x); while (array_[current_pos].info_ != EMPT
size_t FindPos(const HashedObj & x) const {
size_t offset = 1;
size_t current_pos = InternalHash(x);
while (array_[current_pos].info_ != EMPTY && array_[current_pos].element_ != x) {
current_pos += offset;
offset += 2;
if (current_pos >= array_.size())
current_pos -= array_.size();
}
return current_pos;
}
在每次迭代中,您将
偏移量增加2
,因此在n
第次迭代后,if将具有值1+2*n
在每次迭代中,您都要将其添加到当前位置。因此,在第一次迭代中,您将1+0*2
添加到current\u pos
,在第二次迭代中添加1+1*2
,在第三次迭代中添加1+2*2
,依此类推
因此,在主体的第次迭代m
结束时添加到当前位置的总量将是1+2*n
从n=0
到n=m-1
的总和,暂时忽略模运算
使用加法的线性,该和可以写成m+2*和(n表示n=0到m-1)
。剩余的总和可以显示为m*(m-1)/2
,因此总数为
m + 2 * m*(m-1)/2 = m**2
因此,此方法与在每次迭代中使用(当前位置+m**2)%array.size()
相同,m
作为循环计数器,而不修改当前位置
将非常感谢!现在它变得更有意义了。