Let us assume that we want to use a hash table so that we can lookup an address based on the name (first+middle+last) of a person. First, we define a hash function. Without knowing any better, we use the hash function in listing 1.
Listing 1: | hashfunction1 |
We simply add up the ASCII code of all the characters, then mod the sum with max to make sure the return value is between 0 and max-1.
Next, we define an array to store addresses. We define this array according to listing 2.
Listing 2: | hashstructure |
struct _HashTab is the hash table. It is not an array because we want it to encapsulate useful information related to a hash table, such as the number items stored in the hash table. table (as a data member) is the array of struct _HashEntry. Each struct _HashEntry consists of a flags integer and the value.