Sub topic 17
Open Addressing: Linear, Quadratic, and Double Hashing
Assume you know arrays, modular arithmetic, and the basic idea of a hash table. In open addressing, every key is stored inside the table array itself. A collision makes the algorithm try another slot. The sequence of tried slots is called the probe sequence.
Let m be the table size and h(k) be the initial slot for key k. A general probe function is:
\[ h(k,i) = (h(k) + \text{offset}(k,i)) \bmod m \]
where i = 0, 1, 2, ....
Linear Probing
Linear probing checks consecutive slots:
\[ h(k,i) = (h(k) + i) \bmod m \]
For example, with m = 7 and h(k) = 3, the probes are 3, 4, 5, 6, 0, ....
def probe_insert(table, key):
m = len(table)
for i in range(m):
slot = (key % m + i) % m
if table[slot] is None:
table[slot] = key
return slot
raise OverflowError("table full")
table = [None] * 7
for key in [10, 17, 24]:
probe_insert(table, key)
print(table)All three keys initially map to slot 3, so they occupy slots 3, 4, and 5. This creates primary clustering, where long consecutive groups form and make later searches slower.
Quadratic Probing
Quadratic probing uses increasing square offsets:
\[ h(k,i) = (h(k) + c1i + c2i^2) \bmod m \]
The common choice c₁ = 0 and c₂ = 1 checks offsets 0, 1, 4, 9, .... It reduces primary clustering, but keys with the same initial hash still follow the same sequence. This is called secondary clustering.
Quadratic probing may fail to visit every slot, depending on m, c₁, and c₂. Therefore, table-size and parameter choices matter.
Double Hashing
Double hashing uses a second hash function:
\[ h(k,i) = (h1(k) + i h2(k)) \bmod m \]
Different keys usually receive different step sizes, so clustering is lower. The step size must be nonzero. For a table of prime size m, a common choice is h₂(k) = 1 + (k \bmod (m-1)).
Load Factor and Expected Probe Counts
The load factor is:
\[ \alpha = \frac{n}{m} \]
where n is the number of stored keys. As α approaches 1, open addressing becomes slow because fewer empty slots remain.
Under the uniform-hashing assumption, the expected probes are approximately:
| Operation | Expected probes |
|---|---|
| Successful search | \(\frac{1}{2}(1+\frac{1}{1-\alpha})\) |
| Unsuccessful search or insertion | \(\frac{1}{2}(1+\frac{1}{(1-\alpha)^2})\) |
These formulas are estimates. Linear probing often performs worse than the uniform model because of clustering. In practice, resize the table before the load factor becomes too high.
Exercise
A table has 10 slots and 7 stored keys. What is its load factor, and why is another insertion likely to require several probes?
Show answer
The load factor is 7/10 = 0.7. Only three slots are empty, so a collision is likely to require probing through occupied slots.