C Program To Implement Dictionary Using Hashing Algorithms Instant
// Delete a key from the dictionary int delete_key(HashTable *table, const char *key) !key) return 0; // 0 = failureunsigned long hash = hash_djb2(key); int index = hash % table->size; KeyValuePair *current = table->buckets[index]; KeyValuePair *prev = NULL; while (current) if (strcmp(current->key, key) == 0) // Found the node to delete if (prev) prev->next = current->next; else table->buckets[index] = current->next; free(current->key); free(current); table->count--; return 1; // Success prev = current; current = current->next; return 0; // Key not found
In separate chaining, each bucket of the hash table contains a linked list (or another dynamic data structure) of key-value pairs that hash to that index. When a collision occurs, the new pair is simply appended to the list.
Advantages:
Disadvantages:
In C, a chaining-based dictionary might define nodes as:
typedef struct Entry char *key; int value; struct Entry *next; Entry;
Entry *hashTable[TABLE_SIZE];
Insertion involves hashing the key, then prepending or appending to the list at hashTable[index]. Search requires traversing the list until the matching key is found.
Below is a complete, compilable C program. It implements a Dictionary with String keys and Integer values. c program to implement dictionary using hashing algorithms
Searching for keys: banana -> 20 kiwi not found
Deleting 'orange'... 'orange' deleted successfully.
We need a deterministic function that converts a string into an integer. A popular choice is the djb2 algorithm (by Daniel J. Bernstein), which uses bit shifting to generate a well-distributed hash. // Delete a key from the dictionary int
unsigned long hash_function(const char *str)
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
Replace % size with & (size - 1) when size is a power of two.
unsigned long index = hash & (dict->size - 1);
This is much faster than modulus.