Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lecture 05

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Hash Table

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.

Insert Search Delete

Hash Function
Maps keys to positions in the Hash Table. Be easy to calculate. Use all of the key. Spread the keys uniformly.

Example: Hash Function #1


unsigned hash(char* s) { int i = 0; unsigned value = 0; while (s[i] != \0) { value = (s[i] + 31*value) % 101; i++; } return value; }

Example: Hash Function #1


value = (s[i] + 31*value) % 101; A. Aho, J. Hopcroft, J. Ullman, Data Structures and Algorithms, 1983, Addison-Wesley. A = 65 h = 104 o = 111

value = (65 + 31 * 0) % 101 = 65 value = (104 + 31 * 65) % 101 = 99 value = (111 + 31 * 99) % 101 = 49

Example: Hash Function #1


value = (s[i] + 31*value) % 101;
Key Hash Value

Aho Kruse Standish Horowitz Langsam Sedgewick Knuth

49 95 60 28 21 24 44

resulting table is sparse

10

Example: Hash Function #2


value = (s[i] + 1024*value) % 128;
Key Hash Value

Aho Kruse Standish Horowitz Langsam Sedgewick Knuth

111 101 104 122 109 107 104

likely to result in clustering

11

Example: Hash Function #3


value = (s[i] + 3*value) % 7;
Key Hash Value

Aho Kruse Standish Horowitz Langsam Sedgewick Knuth

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

You might also like