BIT201 ยท 2078 ยท 5 marks
Define hashing. Explain quadratic probing with example.
Define hashing. Explain quadratic probing with example. [5]
Quick answer
Hashing is a technique used to map a key to a specific location (index) in a hash table using a hash function. The hash function computes an index from the key, allowing for O(1) average-case time complexity for insertion, deletion, and search operations.
Hashing and Quadratic Probing
Definition of Hashing
Hash Function:
$$h(k) = k \mod m$$
where k is the key and m is the size of the hash table.
A collision occurs when two different keys map to the same index. Various collision resolution techniques are used to handle this.
Quadratic Probing
Quadratic Probing is an open addressing collision resolution technique. When a collision occurs at index h(k), instead of checking the next sequential slot (as in linear probing), it probes slots at quadratic intervals.
Probe Sequence Formula:
$$h_i(k) = (h(k) + i^2) \mod m$$
where:
h(k)= initial hash valuei= probe number (i = 0, 1, 2, 3, ...)m= size of the hash table
Advantage over Linear Probing: Quadratic probing reduces primary clustering (long chains of consecutive filled slots).
Example
Insert the keys: 18, 26, 35, 9, 64 into a hash table of size m = 7
Hash function: h(k) = k mod 7
| Key | h(k) = k mod 7 | Probe | Final Index |
|---|---|---|---|
| 18 | 18 mod 7 = 4 | i=0, slot 4 is empty | 4 |
| 26 | 26 mod 7 = 5 | i=0, slot 5 is empty | 5 |
| 35 | 35 mod 7 = 0 | i=0, slot 0 is empty | 0 |
| 9 | 9 mod 7 = 2 | i=0, slot 2 is empty | 2 |
| 64 | 64 mod 7 = 1 | i=0, slot 1 is empty | 1 |
Now insert key = 26 again (to show collision), suppose we insert key = 19:
h(19) = 19 mod 7 = 5โ slot 5 is occupied (collision!)- Probe i=1:
(5 + 1ยฒ) mod 7 = 6โ slot 6 is empty โ insert at 6
Final Hash Table:
| Index | Key |
|---|---|
| 0 | 35 |
| 1 | 64 |
| 2 | 9 |
| 3 | -- |
| 4 | 18 |
| 5 | 26 |
| 6 | 19 |
Summary
| Feature | Detail |
|---|---|
| Probe formula | h(k, i) = (h(k) + iยฒ) mod m |
| Collision handling | Quadratic jumps |
| Avoids | Primary clustering |
| Drawback | May cause secondary clustering; may not probe all slots if m is not prime |
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.