For most applications, hashing with chaining offers the best balance of speed and simplicity.
We use an array of linked lists (buckets). Each bucket contains all key-value pairs that hash to the same index. This method is simple, handles an arbitrary number of collisions gracefully, and does not require the table to be resized as aggressively as open addressing.
/* Structure for a node in the linked list (key-value pair) */ typedef struct Node char key; / Dynamically allocated key string / int value; / Associated integer value */ struct Node next; / Next node in the chain */ Node; c program to implement dictionary using hashing algorithms
For an educational C program, is often chosen because:
printf("Inserted ('%s', %d) at index %u\n", key, value, idx); For most applications, hashing with chaining offers the
// Create a new hash table HashTable* createHashTable() HashTable* hashTable = (HashTable*) malloc(sizeof(HashTable)); hashTable->buckets = (Node**) malloc(sizeof(Node*) * HASH_TABLE_SIZE); hashTable->size = HASH_TABLE_SIZE; for (int i = 0; i < HASH_TABLE_SIZE; i++) hashTable->buckets[i] = NULL;
The following example uses a simple hash function and separate chaining to handle collisions. This method is simple, handles an arbitrary number
-------------------------------------------------------------*/ void dict_insert(Dict *d, const char *key, int value) unsigned int idx = hash(key, d->size); Node *curr = d->table[idx];
-------------------------------------------------------------*/ int dict_search(const Dict *d, const char *key, int *val) unsigned int idx = hash(key, d->size); Node *curr = d->table[idx];
It should spread the keys evenly across the hash table to prevent clustering.
The hash() function implements djb2. It processes each character of the key, updating the hash value with hash = hash * 33 + c . The final result is taken modulo the table size. This function is fast and gives good distribution for typical English text.