Lecture 08 - Hash Tables
Lecture 08 - Hash Tables
and Algorithms
1
SE1052 - Data Structures and Algorithms
2
Hash Table
• A Hash Table is a data structure that maps keys to values for efficient
lookup.
Why Hash Tables are important
• If you have 100 employees with Emp IDs from 0 to 99, what is the
best way to assign employees to the array.
• If you have 100 employees with Emp IDs from 00000 to 99999, what
is the best way to assign employees to the array.
Hash Tables - Hashing
Example
Given a hash table of size 1000, map the key 12345 to an appropriate location in the
hash table.
Mid-Square Method
• Step 1: Square the value of the key. That is, find k2.
• Step 2: Extract the middle r digits of the result obtained in Step 1.
• Suppose we have a hash table of size 100 (i.e., we need a two-digit hash value)
and we want to hash the key 456.
• Step 1: Square the key:
4562 = 207936
• Step 2: Extract the middle digits: The squared result is 207936. To get the hash
value, extract the middle two digits (in this case, the 3rd and 4th digits).
Folding Method
• Step 1: Divide the key value into a number of parts. That is, divide k into parts k1,
k2, ..., kn, where each part has the same number of digits except the last part
which may have lesser digits than the other parts.
• Step 2: Add the individual parts. That is, obtain the sum of k1 + k2 + ... + kn. The
hash value is produced by ignoring the last carry, if any.
Folding Method
• Given a hash table of 100 locations, calculate the hash value using folding method
for keys 5678, 321, and 34567.
• Since there are 100 memory locations to address, we will break the key into parts
where each part (except the last) will contain two digits. The hash values can be
obtained as shown below:
Collision
• A collision occurs when two (or more) keys map to the same hash index
• Collision resolving methods
1. Open addressing
2. Chaining
Open Addessing
• All elements are stored within the hash table array itself; if a collision
occurs, the algorithm searches for another empty slot according to a
specific probe sequence.
• Linear probing
• Quadratic probing
• Double hasing
Linear probing
Initial hash table After inserting the keys 7, 24, 18, 52, 36, 54, 11, and 23 in a chained
hash table of 9 memory locations using h(k) = k mod m.