Lesson 82: Hash table
Calculate where it goes
- A hashing algorithm turns a record key into a storage location. Here: key MOD 7 gives a slot from 0 to 6.
- To find a record, calculate the same hash: no need to search the whole table.
- A collision happens when two keys get the same slot. This lesson stores the second key in the next free slot (and wraps round after the last one).
| Key | key MOD 7 | Slot |
|---|---|---|
| 1030 | 1 | 1 |
| 1050 | 0 | 0 |
| 1037 | 1 | 2 (collision) |
| 1044 | 1 | 3 (collision) |

In the exam
- 9618/31/M/J/23 Q3: a hashing algorithm uses key modulus 3. (a) Mark scheme: 1030 → 1, 1050 → 0, 1025 → 2. (b) What happens when a hash value is a duplicate? Mark scheme: a collision occurs, so the location is already used by another record; to store, search linearly for the next free space (or use an overflow area); to find, search linearly from that place until the matching key is found; if it is not found, the record is not in the file.
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
A hash table with 7 slots stores record keys. The hash value is key % 7 (key MOD 7). Two keys can get the same slot: a collision. Then try the next slot, and after slot 6 go back to slot 0, until you find an empty slot (0). If all 7 slots are full, print Table full. Type keys in the Serial Monitor.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Now find keys in a full-but-one table. Start at slot key % 7 and move on slot by slot, as when storing. Stop when you find the key, when you reach an ว่างเปล่า slot (the key cannot be further on), or after 7 slots. Print how many slots you checked.
คลิก Run เพื่อดูผลลัพธ์ที่นี่