diff options
| author | Kai Stevenson <kai@kaistevenson.com> | 2023-02-20 22:07:59 -0800 |
|---|---|---|
| committer | Kai Stevenson <kai@kaistevenson.com> | 2023-02-20 22:07:59 -0800 |
| commit | 84ba393f95aa85d975b4bb9f816be4babd1d50d5 (patch) | |
| tree | 1d2ef4b3f75b44ba1b21a75d09fcdcb95097f59c | |
| parent | 7cd204152e388e3462294aafbea4adb626ba9547 (diff) | |
optimized hashtable and fixed a bug
| -rw-r--r-- | src/hashtable.c | 11 | ||||
| -rw-r--r-- | src/hashtable.h | 1 |
2 files changed, 7 insertions, 5 deletions
diff --git a/src/hashtable.c b/src/hashtable.c index 2ec766d..84676a9 100644 --- a/src/hashtable.c +++ b/src/hashtable.c @@ -27,7 +27,6 @@ hashtable_t* init_hashtable(unsigned int capacity, hashtable_t* parent) { return ht; } void destroy_hashtable(hashtable_t* hashtable) { - /* TODO: optimize this */ for (int i = 0; i < hashtable->capacity; i++) { if (hashtable->pairs[i].key != NULL) { free(hashtable->pairs[i].key); @@ -48,9 +47,11 @@ unsigned int get_hash(char* str) { unsigned int hashtable_add_pair(hashtable_t* hashtable, pair_t pair) { unsigned int hash = get_hash(pair.key); for (int i = 0; i < hashtable->capacity; i++) { - pair_t p = hashtable->pairs[hash % hashtable->capacity]; + unsigned int ha = hash + i; + unsigned int ia = ha % hashtable->capacity; + pair_t p = hashtable->pairs[ia]; if (p.key == NULL || strcmp(p.key, pair.key) == 0) { - hashtable->pairs[hash % hashtable->capacity] = pair; + hashtable->pairs[ia] = pair; return hash; } } @@ -69,7 +70,9 @@ unsigned int hashtable_update_pair_recurse(hashtable_t* origin, pair_t pair) { pair_t hashtable_get_pair(hashtable_t* hashtable, char* key) { unsigned int hash = get_hash(key); for (int i = 0; i < hashtable->capacity; i++) { - pair_t p = hashtable->pairs[hash % hashtable->capacity]; + unsigned int ha = hash + i; + unsigned int ia = ha % hashtable->capacity; + pair_t p = hashtable->pairs[ia]; if (p.key != NULL && strcmp(p.key, key) == 0) { return p; } diff --git a/src/hashtable.h b/src/hashtable.h index 6f0dc51..aa387d5 100644 --- a/src/hashtable.h +++ b/src/hashtable.h @@ -9,7 +9,6 @@ pair_t init_pair(char* key, void* value); typedef struct HashTable { pair_t* pairs; int capacity; - int itemCount; struct HashTable* parent; } hashtable_t; hashtable_t* init_hashtable(unsigned int capacity, hashtable_t* parent); |
