C Program To Implement Dictionary Using Hashing Algorithms [ 2024 ]
Deleting 'orange'... 'orange' deleted successfully. === Dictionary Contents (Total: 3 entries) === Bucket[4412]: (grape -> 40) Bucket[9234]: (apple -> 99) Bucket[9876]: (banana -> 20) Total number of key-value pairs: 3 6.1 Dynamic Resizing (Rehashing) A static hash table becomes inefficient when it fills up. The load factor α = count / size should ideally stay below 0.75. Implement rehashing:
printf("==========================================\n"); // Free all memory used by the hash table void destroy_hash_table(HashTable *table) if (!table) return; for (int i = 0; i < table->size; i++) KeyValuePair *current = table->buckets[i]; while (current) KeyValuePair *temp = current; current = current->next; free(temp->key); free(temp); c program to implement dictionary using hashing algorithms
// The hash table structure typedef struct KeyValuePair **buckets; // Array of pointers to linked list heads int size; // Current number of buckets (table size) int count; // Total number of key-value pairs stored HashTable; For strings, one of the most effective and simple algorithms is the DJB2 hash function, created by Daniel J. Bernstein. It provides excellent distribution and is easy to compute. Deleting 'orange'
return table; // Helper: create a new node KeyValuePair* create_pair(const char *key, int value) KeyValuePair *new_pair = (KeyValuePair*)malloc(sizeof(KeyValuePair)); if (!new_pair) return NULL; new_pair->key = strdup(key); // Allocate and copy string new_pair->value = value; new_pair->next = NULL; The load factor α = count / size
// Re-insert all old entries for (int i = 0; i < old_size; i++) KeyValuePair *current = old_buckets[i]; while (current) insert(table, current->key, current->value); KeyValuePair *temp = current; current = current->next; free(temp->key); free(temp);
=== Dictionary Implementation using Hashing in C === Inserting entries... === Dictionary Contents (Total: 4 entries) === Bucket[4412]: (grape -> 40) Bucket[9234]: (apple -> 99) Bucket[9876]: (orange -> 30) (banana -> 20) Searching for keys: banana -> 20 kiwi not found