Sub topic 15
Designing Hash Functions
Assume you know arrays, modular arithmetic, and the basic idea of a hash table. A hash function maps a key to an array index. For a table with m slots, it should produce a value in the range 0 through m - 1.
A good hash function spreads likely keys across the table. Poor spreading creates collisions, where two keys receive the same slot. Collision resolution is handled by chaining or open addressing, but the hash function still determines how often collisions occur.
The Division Method
The division method uses the remainder after division:
\[ h(k) = k \bmod m \]
For example, with m = 11:
\[ h(37) = 37 \bmod 11 = 4 \]
The table size matters. If m is a power of two, only the low-order bits of the key determine the result. Keys with similar low bits can then cluster. A prime table size often gives better mixing, especially when the keys have regular patterns.
The table size should also avoid sharing common factors with the structure of the keys. For example, if keys are mostly multiples of 10, a table size related to 10 can cause repeated positions.
The Multiplication Method
The multiplication method first multiplies the key by a constant A, keeps the fractional part, and scales it by the table size:
\[ h(k) = \lfloor m(kA \bmod 1) \rfloor \]
Here, 0 < A < 1, and x mod 1 means the fractional part of x. A commonly used choice is a constant near the reciprocal of the golden ratio:
\[ A \approx 0.6180339887 \]
Unlike the division method, this method is less sensitive to the exact table size. The same multiplier can work with several table sizes, although the key distribution still matters.
def division_hash(key, table_size):
return key % table_size
def multiplication_hash(key, table_size, multiplier=0.6180339887):
fraction = (key * multiplier) % 1
return int(table_size * fraction)
keys = [10, 21, 32, 43]
for key in keys:
print(key, division_hash(key, 11), multiplication_hash(key, 11))Choosing a Method
| Method | Formula | Main concern |
|---|---|---|
| Division | `k mod m` | Poor table sizes can preserve key patterns |
| Multiplication | `floor(m * frac(kA))` | The multiplier and key type still affect distribution |
For string keys, convert characters into numbers before hashing. A polynomial hash is common:
\[ h(s) = (s0b^{n-1} + s1b^{n-2} + \cdots + s_{n-1}) \bmod m \]
Using a base b makes character order matter. For example, cat and act should normally receive different values.
Exercise
For a table of size 13, what slot does the division method assign to key 91?
Show answer
The slot is 91 mod 13 = 0.