Constructing Hash Functions
Hash Functions for Numeric Keys
Several common methods are available for constructing hash functions for numeric keys:
Direct Addressing
Use a linear function of the key as the hash address.
For example, population counts by birth year use h(key) = key - 1990:
| Address | Birth year | Population |
|---|---|---|
| 0 | 1990 | 1285 × 10,000 |
| 1 | 1991 | 1281 × 10,000 |
| 2 | 1992 | 1280 × 10,000 |
| 10 | 2000 | 1250 × 10,000 |
| 21 | 2011 | 1180 × 10,000 |
Direct addressing
KNOWLEDGE QUIZ
Division Method
The hash function is h(key) = key % p, where p is usually prime.
For example, h(key) = key % 17:
| Address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Key | 34 | 18 | 2 | 20 | 23 | 7 | 42 | 27 | 11 | 30 | 15 |
Division method
KNOWLEDGE QUIZ
Digit Analysis
Analyze how digits vary at different positions in numeric keys, and choose relatively random positions as the hash address.
For example, use the last four digits of an 11-digit phone number: h(key) = key % 10000.
As another example, choose relatively random positions in an 18-digit identity number:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 3 | 3 | 0 | 1 | 0 | 6 | 1 | 9 | 9 | 0 | 1 | 0 | 0 | 8 | 0 | 4 | 1 | 9 |
| Province | City | District | Year | Month | Day | Sequence | Check | ||||||||||
Digit analysis
Folding
Split the key into groups with the same number of digits, then add them together.
For example, split the integer 56793542 into groups of three digits:
| Operation | Value |
|---|---|
| 542 | |
| 793 | |
| + | 056 |
| = | 1391 |
KNOWLEDGE QUIZ
Mid-Square Method
Square the key and take several middle digits.
For example, the integer 56793542:
| Operation | Value |
|---|---|
| 56793542 | |
| * | 56793542 |
| = | 3225506412905764 |
Hash Functions for String Keys
Several common methods are available for constructing hash functions for string keys:
ASCII Sum
However, some strings produce severe collisions, such as a3, b2, c1, or eat and tea.
KNOWLEDGE QUIZ
Shifting
Apply positional weights to the first three characters.
Some strings still collide, such as string, strong, street, and structure.
An effective improvement is to include all n characters of the key:
String hashing: calculate and compare
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
Folding: hash a new set of keys
Use only folding for the sequence 724186035, 186035724, 905417236. Split each key into three-digit groups from the right, sum the groups, and take the last three digits: h(key) = group sum % 1000.
- Show each key’s groups, sum, and final address.
- Identify which keys collide and explain why.