First you need to think about your collision strategy:
- Will you have several hash functions?
- Or do you have to use containers inside a hash table?
We will choose 1.
Then you need to select a well-distributed hash function. For example, we will choose
int hash_fun(int key, int try, int max) { return (key + try) % max; }
If you need something better, maybe look at the middle square method.
Then you have to decide what the hash table is.
struct hash_table { int max; int number_of_elements; struct my_struct **elements; };
Then we need to determine how to insert and extract.
int hash_insert(struct my_struct *data, struct hash_table *hash_table) { int try, hash; if(hash_table->number_of_elements >= hash_table->max) { return 0; // FULL } for(try = 0; true; try++) { hash = hash_fun(data->key, try, hash_table->max); if(hash_table->elements[hash] == 0) { // empty cell hash_table->elements[hash] = data; hash_table->number_of_elements++; return 1; } } return 0; } struct my_struct *hash_retrieve(int key, struct hash_table *hash_table) { int try, hash; for(try = 0; true; try++) { hash = hash_fun(key, try, hash_table->max); if(hash_table->elements[hash] == 0) { return 0; // Nothing found } if(hash_table->elements[hash]->key == key) { return hash_table->elements[hash]; } } return 0; }
And the smallest removal method:
int hash_delete(int key, struct hash_table *hash_table) { int try, hash; for(try = 0; true; try++) { hash = hash_fun(key, try, hash_table->max); if(hash_table->elements[hash] == 0) { return 0; // Nothing found } if(hash_table->elements[hash]->key == key) { hash_table->number_of_elements--; hash_table->elements[hash] = 0; return 1; // Success } } return 0; }
marc
source share