This report presents the design and implementation of a dictionary data structure in the C programming language using hashing techniques. A dictionary, also known as a symbol table or associative array, stores key-value pairs and supports efficient insertion, search, and deletion operations. Hashing provides average-case O(1) time complexity for these operations. This implementation uses separate chaining to handle collisions and a simple polynomial rolling hash function for strings.
Simple, fast, and provides good distribution. c program to implement dictionary using hashing algorithms
unsigned long hash_djb2(const char *str)
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
To take your dictionary to the next level, consider these improvements: Essay: Implementing a Dictionary Using Hashing Algorithms in
int get(Dictionary* dict, const char* key, int* found)
int index = hash(key, dict->size);
Entry* curr = dict->buckets[index];
while (curr != NULL)
if (strcmp(curr->key, key) == 0)
*found = 1;
return curr->value;
curr = curr->next;
*found = 0;
return -1;
Deletion requires careful pointer management. Memory leaks - Always free keys and entries
int delete_key(Dictionary *dict, const char *key) unsigned long hash = dict->hash_func(key); unsigned long index = hash % dict->size;Entry *curr = dict->buckets[index]; Entry *prev = NULL; while (curr) if (strcmp(curr->key, key) == 0) if (prev) prev->next = curr->next; else dict->buckets[index] = curr->next; free(curr->key); free(curr->value); free(curr); dict->count--; return 1; // Success prev = curr; curr = curr->next; return 0; // Key not found
For string keys, we use a polynomial hash: [ \texthash = \sum_i=0^n-1 \textstr[i] \times p^i \mod M ] Where ( p ) is a prime (e.g., 31 or 131), and ( M ) is the table size (a prime number to distribute keys better).