Well, the key doesn't have to be a string. It could be anything, for instance an int. Here is one of the simplest examples of a hash function.
- Code: Select all
int
hash (int key)
{
return key;
}
Of course when it is this simple you would think it isn't really necessary, but actually using a function to return the index means you can later change the hash function and not have to change anything else (one of the reasons you want to use functions). Now the method you create the index from the key is up to you. There are plenty of different ways to create the index. The above example shows a perfect hash (meaning for every unique key, there would be a unique index). When using a hashed array, you do run into some minor problems. For instance, you only have storage for a finite number of storage points.
Using the same example, just say the array was only of size 10. In that case you need the hash function to never return larger indexes.
- Code: Select all
int
hash (int key)
{
return key%10; // only returns 0-9
}
As you might note, this means that if you plug in 0 and 10, they will return the same index. That is what is called a collision. There are various methods to resolve a collision. But, a simple hash function for strings, that is pretty good is this.
- Code: Select all
int
hash (char* key)
{
int i;
int len = strlen(key);
int index = 0;
for(i=0;i<len;i++)
{
index+=key[i];
}
return index%HASH_SIZE; // replacing HASH_SIZE with the size of the hashed array
}