gpt4 book ai didi

c - C中的重新散列函数

转载 作者:太空宇宙 更新时间:2023-11-04 08:18:03 25 4
gpt4 key购买 nike

我正在做一个哈希表并实现了以下哈希函数

int linesn=8;
int hash(char *str, int table_size)
{
int sum;

// Make sure a valid string passed in
if (str==NULL) return -1;

// Sum up all the characters in the string
for( ; *str; str++) sum += *str;

// Return the sum mod the table size
return sum % table_size;
}

char *str="Carlos";
int hashv=hash(str,linesn);
printf("\nThe hash value is: %d",hashv);

由于存在任何散列函数冲突,如何实现重新散列函数来防止这些冲突,我在 Google 上阅读过,但示例对我来说很复杂,请任何人给我一个想法。

提前致谢

最佳答案

散列是一个非常有趣的话题。我建议您阅读 Cormen。解释的很清楚。

我会给你一个简单方法的想法--

Here simply take a counter and whenever a element is inserted then increase it. Now if 75% of the table is filled then you just double the size of the array. Allocate twice an array. Now you just again rehash everything using new table size. That's how you do it.

为避免冲突,您可以使用更好的哈希函数。

Another thing incase you have collision just move to the next unfilled one. As <75% is filled in worst case you will get an empty slot. Try this. It is not that good but it works.

关于c - C中的重新散列函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34703016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com