C++ program for hashing with chaining
In hashing there is a hash function that maps keys to some values. But these hashing function may lead to collision that is two or more keys are mapped to same value. Chain hashing avoids collision. The idea is to make each cell of hash table point to a linked list of records that have same hash function value.
Let’s create a hash function, such that our hash table has ‘N’ number of buckets.
To insert a node into the hash table, we need to find the hash index for the given key. And it could be calculated using the hash function.
Example: hashIndex = key % noOfBuckets
Insert: Move to the bucket corresponds to the above calculated hash index and insert the new node at the end of the list.
Delete: To delete a node from hash table, calculate the hash index for the key, move to the bucket corresponds to the calculated hash index, search the list in the current bucket to find and remove the node with the given key (if found).
0 1 --> 15 --> 8 2 3 4 --> 11 5 6 --> 27
Search : O(1+(n/m))
Delete : O(1+(n/m))
where n = Number of slots in Hash table
m = Number of keys to be inserted
Here n/m is the Load Factor.
Load Factor (∝) must be as small as possible.