Lecture 05
Lecture 05
Lecture 05
Hashing
hash table
0 1
key
hash function
pos
2 3
: :
TABLESIZE - 1
2
Example:
hash table
0 1
Kruse
hash function
2 3 4 5 6
3
Kruse
Hashing
Each item has a unique key. Use a large array called a Hash Table. Use a Hash Function.
Applications
Databases. Spell checkers. Computer chess games. Compilers.
Operations
Initialize
all locations in Hash Table are empty.
Hash Function
Maps keys to positions in the Hash Table. Be easy to calculate. Use all of the key. Spread the keys uniformly.
value = (65 + 31 * 0) % 101 = 65 value = (104 + 31 * 65) % 101 = 99 value = (111 + 31 * 99) % 101 = 49
49 95 60 28 21 24 44
10
11
0 5 1 5 5 2 1
collisions
12
Insert
Apply hash function to get a position. Try to insert key at this position. Deal with collision.
13
Example: Insert
Aho, Kruse, Standish, Horowiz, Langsam, Sedgewick, Knuth
hash table
0 1 Aho
Aho
Hash Function
2 3 4 5 6
14
Example: Insert
Aho, Kruse, Standish, Horowiz, Langsam, Sedgewick, Knuth
hash table
0 1 Aho
Kruse
Hash Function
2 3 4 5 6
15
Kruse
Example: Insert
Aho, Kruse, Standish, Horowiz, Langsam, Sedgewick, Knuth
hash table
0 1 Aho Standish
Standish
Hash Function
2 3 4 5 6
16
Kruse
Search
Apply hash function to get a position. Look in that position. Deal with collision.
17
Example: Search
Aho, Kruse, Standish, Horowiz, Langsam, Sedgewick, Knuth
hash table
0 1 Aho Standish
Kruse
Hash Function
2 3 4 5 Kruse
found.
6
18
Example: Search
Aho, Kruse, Standish, Horowiz, Langsam, Sedgewick, Knuth
hash table
0 1 Aho Standish
Sedgwick
Hash Function
2 3 4 5 Kruse
Not found.
6
19