Using chain is one solution for collision. Each element in array of hash table is a linked list, which store all the key_value pair that share the same hash. Initially, all slots of array will be NULL. For push in a pair of key-value, hash value is calculated, then the pair will be added at the end of the linked list of corresponding hash value.
Illustration:
![[600] [500]](/static/img/hash_illustration.jpg)
Source: www.necessaryandsufficient.net
Complexity
Assume that the distribution of value in hash code is urniform, basic operations (such as get, set, remove) will be TABLE_SIZE time faster than storing all key-value linearly.
Implementation
- In the implementation below, key-value pairs are assumed to be int-int.
- TABLE_SIZE (size of hash array) = 128
1 | #include <stdio.h> |