2078 11

BIT201 ยท 2078 ยท 5 marks

Define hashing. Explain quadratic probing with example.

Define hashing. Explain quadratic probing with example. [5]

Data Structures and AlgorithmsChapter 7: Searching and HashingQuadratic probing collision resolution

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 value
  • i = 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

Keyh(k) = k mod 7ProbeFinal Index
1818 mod 7 = 4i=0, slot 4 is empty4
2626 mod 7 = 5i=0, slot 5 is empty5
3535 mod 7 = 0i=0, slot 0 is empty0
99 mod 7 = 2i=0, slot 2 is empty2
6464 mod 7 = 1i=0, slot 1 is empty1

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:

IndexKey
035
164
29
3--
418
526
619

Summary

FeatureDetail
Probe formulah(k, i) = (h(k) + iยฒ) mod m
Collision handlingQuadratic jumps
AvoidsPrimary clustering
DrawbackMay 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.