字符串hash函数
轉自 http://www.cppblog.com/shyli/archive/2007/04/07/21455.html 字符串hash函數 字符串hash函數,解決沖突用開放定址法,每次對哈希值加1
在下列程序中,不是按常規方法用哈希表來記錄關鍵字,
而是用整型數組Htable記錄關鍵字在字符串ch中的位置。
在插入時不用把關鍵字復制到哈希表中,只是記錄一個索引,從而提高了效率。
當查詢時,只要把Htable的值映射到字符串ch中就可以了。
注意ch的下標要從1開始,因為Htable中的零值認為是空,處理起來比較方便。 #include<iostream>
#include<string>
using?Namespace?stdnamespace?std;
const?int?MAXN?=?9973;?//哈希表長度
const?int?len?=?30;?//字符串的最大長度
int?Htable[MAX];
char?ch[MAX][len];?//存儲關鍵字的字符串
unsigned?long?Hash(char?*?key)
{
????unsigned?long?h?=?0;
????while(*key)
????{
????????h?=?(h?<<?4)?+?*key++;
????????unsigned?long?g?=?h?&?0xf0000000L;
????????if(g)
????????????h?^=?g?>>?24;
????????h?&=?~g;
????}
????return?h?%?MAX;
}
int?search(char?*?key)
{
????unsigned?long?i?=?Hash(key);
????while(Htable[i])
????{
????????if(strcmp(ch[Htable[i]],?key)?==?0)
????????????return?i;
????????i?=?(i?+?1)?%?MAX;
????}
????return?-1;
}
int?insert(char?*?key,?int?j)?//j為關鍵字在ch中的位置,即索引
{
????unsigned?long?i?=?Hash(key);
????while(Htable[i])
????????i?=?(i?+?1)?%?MAX;
????Htable[i]?=?j;
????return?i;
} ?
在下列程序中,不是按常規方法用哈希表來記錄關鍵字,
而是用整型數組Htable記錄關鍵字在字符串ch中的位置。
在插入時不用把關鍵字復制到哈希表中,只是記錄一個索引,從而提高了效率。
當查詢時,只要把Htable的值映射到字符串ch中就可以了。
注意ch的下標要從1開始,因為Htable中的零值認為是空,處理起來比較方便。 #include<iostream>
#include<string>
using?Namespace?stdnamespace?std;
const?int?MAXN?=?9973;?//哈希表長度
const?int?len?=?30;?//字符串的最大長度
int?Htable[MAX];
char?ch[MAX][len];?//存儲關鍵字的字符串
unsigned?long?Hash(char?*?key)
{
????unsigned?long?h?=?0;
????while(*key)
????{
????????h?=?(h?<<?4)?+?*key++;
????????unsigned?long?g?=?h?&?0xf0000000L;
????????if(g)
????????????h?^=?g?>>?24;
????????h?&=?~g;
????}
????return?h?%?MAX;
}
int?search(char?*?key)
{
????unsigned?long?i?=?Hash(key);
????while(Htable[i])
????{
????????if(strcmp(ch[Htable[i]],?key)?==?0)
????????????return?i;
????????i?=?(i?+?1)?%?MAX;
????}
????return?-1;
}
int?insert(char?*?key,?int?j)?//j為關鍵字在ch中的位置,即索引
{
????unsigned?long?i?=?Hash(key);
????while(Htable[i])
????????i?=?(i?+?1)?%?MAX;
????Htable[i]?=?j;
????return?i;
} ?
轉載于:https://www.cnblogs.com/marsmars/archive/2008/02/18/2298976.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
- 上一篇: 什么情况导致全表扫描,而不是用索引 收藏
- 下一篇: Address already in u