Hi! this is my first tutorial and I'm going to explain how hashing and hash table works and how to use it. OK, but what is Hash Table actually and how can it benefit us? well, a Hash Table is a type of table in which we can use each record's id to retrieve the it's data easily. So, each record must have a unique id, which is going to be an int higher than or equal to 1. And another thing to mention, we use a value of -1 for id for each empty record's id.

Hash Function
For this tutorial, I used the following simple function to hash a given id:

hash(id) = id%size;

size is the length of our table, which has to be a prime number. I used 51 in this tutorial. The reason why it needs to be prime is that, if we don't use a prime number, the resulting hashed value will be zero for each id divideable by size. But if we use a prime number for size, then we decrease the chance of id being divideable by size.

Collisions

When inserting items into a hash table, it sometimes happens that an item to be inserted in table has a hash value that points to an already existing location in table. The new item typically is inserted somewhere else, though we must be sure that there is still a way to look up the item.

One of the simplest ways to overcome collisions is to use a rehash function:

rehash(id) = (id+1)%size;

Note: When we hash an id and check and see that it is already taken, we give the hashed id to rehash function.

OK, now here's an example program I wrote to implement a hash table and function. It's quite straight forward but I commented it too:

In this tutorial, I used a simple hash function which was good enough for working with integer values, but what if we want to hash strings ? Yup we need a more advanced function to do that. There are many ways to do that which is beyond this tutorial's goals. But at least you are now familiar with the way hashing works. Hope this tutorial helped you!