經常使用的哈希函數
通用的哈希函數庫有下面這些混合了加法和一位操做的字符串哈希算法。下面的這些算法在用法和功能方面各有不一樣,可是均可以做爲學習哈希算法的實現的例子。
1.RS
從Robert Sedgwicks的 Algorithms in C一書中獲得了。已經添加了一些簡單的優化的算法,以加快其散列過程。
- public long RSHash(String str)
- {
- int b = 378551;
- int a = 63689;
- long hash = 0;
- for(int i = 0; i < str.length(); i++)
- {
- hash = hash * a + str.charAt(i);
- a = a * b;
- }
- return hash;
- }
2.JS
Justin Sobel寫的一個位操做的哈希函數。
- public long JSHash(String str)
- {
- long hash = 1315423911;
- for(int i = 0; i < str.length(); i++)
- {
- hash ^= ((hash << 5) + str.charAt(i) + (hash >> 2));
- }
- return hash;
- }
3.PJW
該散列算法是基於貝爾實驗室的彼得J溫伯格的的研究。在Compilers一書中(原則,技術和工具),建議採用這個算法的散列函數的哈希方法。
- public long PJWHash(String str)
- {
- long BitsInUnsignedInt = (long)(4 * 8);
- long ThreeQuarters = (long)((BitsInUnsignedInt * 3) / 4);
- long OneEighth = (long)(BitsInUnsignedInt / 8);
- long HighBits = (long)(0xFFFFFFFF) << (BitsInUnsignedInt - OneEighth);
- long hash = 0;
- long test = 0;
- for(int i = 0; i < str.length(); i++)
- {
- hash = (hash << OneEighth) + str.charAt(i);
- if((test = hash & HighBits) != 0)
- {
- hash = (( hash ^ (test >> ThreeQuarters)) & (~HighBits));
- }
- }
- return hash;
- }
4.ELF
和PJW很類似,在Unix系統中使用的較多。
- public long ELFHash(String str)
- {
- long hash = 0;
- long x = 0;
- for(int i = 0; i < str.length(); i++)
- {
- hash = (hash << 4) + str.charAt(i);
- if((x = hash & 0xF0000000L) != 0)
- {
- hash ^= (x >> 24);
- }
- hash &= ~x;
- }
- return hash;
- }
5.BKDR
這個算法來自Brian Kernighan 和 Dennis Ritchie的 The C Programming Language。這是一個很簡單的哈希算法,使用了一系列奇怪的數字,形式如31,3131,31...31,看上去和DJB算法很類似。(這個就是Java的字符串哈希函數)
- public long BKDRHash(String str)
- {
- long seed = 131;
- long hash = 0;
- for(int i = 0; i < str.length(); i++)
- {
- hash = (hash * seed) + str.charAt(i);
- }
- return hash;
- }
6.SDBM
這個算法在開源的SDBM中使用,彷佛對不少不一樣類型的數據都能獲得不錯的分佈。
- public long SDBMHash(String str)
- {
- long hash = 0;
- for(int i = 0; i < str.length(); i++)
- {
- hash = str.charAt(i) + (hash << 6) + (hash << 16) - hash;
- }
- return hash;
- }
7.DJB
這個算法是Daniel J.Bernstein 教授發明的,是目前公佈的最有效的哈希函數。
- public long DJBHash(String str)
- {
- long hash = 5381;
- for(int i = 0; i < str.length(); i++)
- {
- hash = ((hash << 5) + hash) + str.charAt(i);
- }
- return hash;
- }
8.DEK
由偉大的Knuth在《編程的藝術 第三卷》的第六章排序和搜索中給出。
- public long DEKHash(String str)
- {
- long hash = str.length();
- for(int i = 0; i < str.length(); i++)
- {
- hash = ((hash << 5) ^ (hash >> 27)) ^ str.charAt(i);
- }
- return hash;
- }
9.AP
這是Arash Partow貢獻的一個哈希函數,繼承了上面以旋轉覺得和加操做。代數描述: