CIE AS & A Level Computer Science, section 13.2 (File organisation and access)
What hashing is
A hashing algorithm takes a record's key and calculates the address (position) where the record is stored. It allows direct access to a record without searching.
A simple hash function
Address ← Key MOD 10
Keys 23, 47 and 51 give addresses 3, 7 and 1. The same key always gives the same address.
Collisions
A collision happens when two different keys give the same address. For example, 23 and 43 both give address 3. The collision must be handled.
Linear probing (open addressing)
Use the next free position after the calculated address (wrapping round at the end).
Other methods
- Chaining: each address holds a list of the records that hash to it.
- Using an overflow area for records that collide.
Example: linear probing
The keys 23, 47, 43, 51 and 33 are inserted in that order into a table of 10 addresses, using Key MOD 10. 23, 47 and 51 go to addresses 3, 7 and 1. 43 collides with 23, so goes to the next free address, 4, and 33 collides with both 23 and 43, so goes to 5.
Good hash functions
A good function spreads keys evenly (to reduce collisions) and is quick to calculate.
Common mistake: forgetting that, with linear probing, a search must follow the same probing as the insert. If the record is not at its calculated address, check the next ones until you find it or reach an empty place.
Exam tip: in a hashing question, work out each address in turn, and state when a collision occurs and where the record goes. Show the final table.
Check yourself
Using Key MOD 10, what is the address of key 47?
.
What is a collision?
When two different keys are hashed to the same address.
Describe one way of dealing with a collision.
Linear probing, which stores the record in the next free position, or chaining, which stores a list of records at the address.