开发者

how to pick a modulo for integer or string hash?

开发者 https://www.devze.com 2023-04-12 17:42 出处:网络
Typically, we do hashing by calculating the integer or string according to a ru开发者_JS百科le, then return hash(int-or-str) % m as the index in the hash table, but how do we choose the modulo m? Is t

Typically, we do hashing by calculating the integer or string according to a ru开发者_JS百科le, then return hash(int-or-str) % m as the index in the hash table, but how do we choose the modulo m? Is there any convention to follow?


There are two possible conventions. One is to use a prime number, which yields good performance with quadratic probing.

The other is to use a power of two, since n mod m where m = 2^k is a fast operation; it's a bitwise AND with m-1. Of course, the modulus must be equal to the size of the hash table, and powers of two mean your hash table must double in size whenever it's overcrowded. This gives you amortized O(1) insertion in a similar way that a dynamic array does.


Since [val modulo m] is used as an index into the table, m is the number of elements in that table. Are you free to choose that ? Then use a big enough prime number. If you need to resize the table, you can either chose to use a bigger prime number, or (if you choose doubling the table for resizing) you'd better make sure that your hash function has enough entropy in the lower bits.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号