Explain how a hash table that uses linear probing stores a new key and later finds it.
Show the markscheme
Markscheme (4 marks)
- A hash function calculates a bucket index from the key (e.g. key mod table size).
- If that bucket is empty the key is stored there; if it is occupied (a collision), the next bucket is tried, (h + 1) mod n, wrapping round to 0, until an empty bucket is found.
- To find the key, the same hash index is calculated and the buckets are checked in the same order from there.
- The search stops when the key is found, or when an empty bucket is reached / the whole table has been checked, meaning the key is not present.
- As the load factor rises, clusters of full buckets form and the probe sequences become longer / slower.
- (Award [1] per point, max 4.)
A full-marks answer
The hash function turns the key into a bucket index, for example key mod n for a table of n buckets. If that bucket is empty, the key is stored there. If it is already occupied, a collision has happened, so the table tries the next bucket, (h + 1) mod n, and keeps moving forward, wrapping round from the last bucket to bucket 0, until it finds an empty one, where the key is stored. To find the key later, the same hash index is calculated and the same sequence of buckets is checked. The search succeeds when it reaches the key and fails when it reaches an empty bucket, because the key would have been stored there. As the table fills up, clusters of occupied buckets make these sequences longer, which is why the load factor is kept low.