The Hash Function
"Hash function" is the first building block of a hash table. Let's see how it works!
We'll cover the following...
Restricting the key size
In the last lesson, you learned that an array could be used to implement a hash table in C#. A key is used to map a value on the array, and the efficiency of a hash table depends on how a key is computed. At first glance, you may observe that you can directly use the indices as keys because each index is unique.
The only problem is that the key would eventually exceed the size of the array. At every insertion, the array would need to be resized. You can increase the array size by increasing their capacity exponentially, but the process still takes O(n) time because it will copy all the elements into the new array.
In order to limit the range of the keys to the boundaries of the array, you need a function that converts a large key into a smaller key. This is the job of the hash function.
What hash functions do?
Take a look at the following illustration to get the analogy of a hash function.
A hash function simply takes an item’s key and returns the corresponding index in the array for that item. Depending on your program, the calculation of this index can be simple arithmetic or a very complicated encryption method. However, it is important to choose an efficient hashing function as it directly affects the performance of the hash table mechanism.
Take a look at some of the most common hash functions used in modern programming. ...