Do you have enough of these properties ?:
- no collisions
- Worst key search performance =>
O(log n)
then the implementation of the evidence-based concept:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_PAIRS 3 #define KEY_SIZE 20 #define VALUE_OR_KEY_NOT_FOUND(v) ((v==NULL)? "(__KEY_NOT_FOUND__)":v) typedef struct { char Key[KEY_SIZE]; char Val[KEY_SIZE]; } Pair; typedef struct { unsigned int lastPairIndex; Pair pairs[MAX_PAIRS]; } HashTable; int comparePairs(const void * a, const void * b) { return strcmp(((Pair *)a)->Key, ((Pair *)b)->Key); } void hashInsert(HashTable * hashTable, char * key, char * val) { unsigned int ix = hashTable->lastPairIndex++; strcpy(hashTable->pairs[ix].Key,key); strcpy(hashTable->pairs[ix].Val,val); } void hashFinalize(HashTable * hashTable) { qsort(hashTable->pairs, MAX_PAIRS, sizeof(Pair), comparePairs); } char * hashLookup(HashTable * hashTable, char * key) { char * r = bsearch(key, hashTable->pairs, MAX_PAIRS, sizeof(Pair), comparePairs); if (r != NULL) return r + KEY_SIZE; return NULL; } int main() { HashTable ht = {0}; char * res; char * key_1 = "jkl"; char * key_2 = "oops"; hashInsert(&ht, "jkl", "some val"); hashInsert(&ht, "def", "other val"); hashInsert(&ht, "abc", "this val"); hashFinalize(&ht); res = hashLookup(&ht, key_1); printf("\"%s\" key => value: \"%s\"\n", key_1, VALUE_OR_KEY_NOT_FOUND(res)); res = hashLookup(&ht, key_2); printf("\"%s\" key => value: \"%s\"\n", key_2, VALUE_OR_KEY_NOT_FOUND(res)); return 0; }
Many errors are not checked - for example, when pasting - the same key already exists. This is just a proof of concept. O(log n) key search performance is achieved because the keys are sorted alphabetically, and thus, key searches can be performed using a binary search algorithm. NTN!
source share