Linear probing: inserting a key
-
When inserting a key K in a table of size M, with hash function H(K)
1. Set indx = H(K)
2. If table location indx already contains the key, no need to insert it. Done!
3. Else if table location indx is empty, insert key there. Done!
4. Else collision. Set indx = (indx + 1) mod M.
5. If indx == H(K), table is full! (Throw an exception, or enlarge table.) Else go to 2.
-
So, linear probing basically does a linear search for an empty slot when there is a collision
-
Advantages: easy to implement; always finds a location if there is one; very good average-case performance when the table is not very full
-
Disadvantages: “clusters” or "clumps" of keys form in adjacent slots in the table; when these clusters fill most of the array, performance deteriorates badly as the probe sequence performs what is essentially an exhaustive search of most of the array
CONTENTS PREVIOUS NEXT