C Program To Implement Dictionary Using Hashing Algorithms
The following program implements a robust, memory-safe dictionary using the hashing algorithm and separate chaining.
Run the dictionary with 100,000 insertions and measure average time per operation using clock() or gettimeofday() .
=== Dictionary Contents (Total: 3 entries) === Bucket[4412]: (grape -> 40) Bucket[9234]: (apple -> 99) Bucket[9876]: (banana -> 20)
void display(HashTable *table) printf("\nDictionary contents:\n"); for (int i = 0; i < table->size; i++) Entry *current = table->buckets[i]; if (current) printf("Bucket %d: ", i); while (current) printf("(%s -> %d) ", current->key, current->value); current = current->next;
void insert(char *key, int value) unsigned long idx = hash(key); Entry *newEntry = malloc(sizeof(Entry)); newEntry->key = strdup(key); newEntry->value = value; newEntry->next = table[idx]; table[idx] = newEntry; // Prepend to chain c program to implement dictionary using hashing algorithms
current = current->next;
Enter your choice: 4
The Dict structure holds the hash table (an array of Node* ) and its size. We also keep a count for the total number of entries.
return hash;
Chaining with linked lists ensures that multiple keys can coexist at the same index, preventing data loss when collisions occur. Time Complexity: Average Case:
// Delete a key from the dictionary int delete_key(HashTable *table, const char *key)
new_pair->next = table->buckets[index]; table->buckets[index] = new_pair; table->count++;
// Insert some key-value pairs printf("Inserting entries...\n"); insert(dict, "apple", 10); insert(dict, "banana", 20); insert(dict, "orange", 30); insert(dict, "grape", 40); insert(dict, "apple", 99); // Update existing key We also keep a count for the total number of entries
You can test the program with various scenarios:
This approach ensures that inserting an existing key becomes an update, while a new key is added without duplicates.
We covered: