insert(dict, "apple", "fruit"); insert(dict, "banana", "fruit"); insert(dict, "carrot", "vegetable");
// Function to delete a key-value pair from the dictionary void delete(Dictionary* dict, char* key) int index = hash(key, dict->size); DictionaryEntry* entry = dict->table[index]; DictionaryEntry* prev = NULL;
int *search(char *key) unsigned long idx = hash(key); Entry *current = table[idx]; while (current) if (strcmp(current->key, key) == 0) return ¤t->value; current = current->next;
// Inserting values insert(&ht, 1, 100); insert(&ht, 2, 200); insert(&ht, 11, 1100); // Collision: 11 % 10 = 1 (chains with key 1) insert(&ht, 21, 2100); // Collision: 21 % 10 = 1 (chains with key 1 and 11) insert(&ht, 5, 500); c program to implement dictionary using hashing algorithms
// Case B: Key does not exist. Create a new node. KeyValue *new_node = (KeyValue*)malloc(sizeof(KeyValue)); new_node->key = duplicate_string(key); new_node->value = value;
In the main function, notice the call to print_dictionary . Because we used Separate Chaining, you can visually see collisions. If "apple" and "banana" (hypothetically) hashed to the same index, the output would show:
Dictionaries are fundamental data structures used in compilers, databases, caches, and many system-level applications. While C does not provide a built-in dictionary type, implementing one using hashing is a classic systems programming exercise. The primary challenges are: Because we used Separate Chaining, you can visually
Ready to take it further? Implement open addressing with quadratic probing, or add a for_each function to iterate over all key-value pairs. Happy coding!
: Common practices include multiplying the hash value by a prime number (e.g., 31) at each step to spread the bits effectively. Modulo Operation : Ensure the final hash is taken modulo the table size ( ) to stay within array bounds. Data Types unsigned int
return dict;
return hash_value % table_size;
// 3. Search / Lookup // Returns pointer to value so we can check for NULL if key not found int* get(Dictionary *dict, const char *key) unsigned long index = hash(key); KeyValue *current = dict->table[index];
prev = current; current = current->next; The primary challenges are: Ready to take it further
Instead of storing just one value at an index, we store a linked list of all key-value pairs that hash to that same index. Separate chaining is generally more robust and will be the focus of the implementation below. C Implementation: Dictionary using Separate Chaining
Use a linked list for "Separate Chaining" to handle collisions. This allows multiple entries to exist at the same index.