C语言 如何检查二次探测是否进入无限循环?



我正在编写一个关于使用二次探测进行哈希和解决碰撞的程序。当我反复插入以相同数字结尾的键时,它会进入某个键的无限循环。这意味着该值无法插入到哈希表中。每当发生这种情况时,我都想通知用户无法将密钥插入哈希表中。如何在代码中为此设置条件。这是我的二次探测函数。

/*Here el is the element to be inserted and loc is the value of hash function and size is 
10*/  
void quadratic(int el)
{
int loc=el%size;
int i=0;
while(hash[loc])
{
if(hash[loc]==el)
{
printf("This key is already present in the tablen");
return;
}
if(i==0)
printf("Collision at %dn",loc );
else
printf("%dth probe at %dn",i,(loc+i*i)%7);
loc=(loc+i*i)%7;
i++;
}
hash[loc]=el;
}

你可以用一个很酷的数学技巧来防止它进入无限循环。

首先,确保地图的大小为 3 mod 4。

然后,而不是添加 1、4、9、...

添加 1, -4, 9, -16, ...

这将访问地图中的每个空间!

最新更新