c - What happens if hash is unique but hash % size is same in hash table? -


recently i'm studying hash table, , understand basis is

  1. create array, example

    hashtable ht[4];

  2. hash key

    int hash = hash_key(key);

  3. get index

    int index = hash % 4

  4. set hashtable

    ht[index] = insert_or_update(value)

and know there hash collision problem, if key1 , key2 has same hash, go same ht[index], separate chaining can solve this.

keys same hash go same bucket, these keys stored in linked list.

my question is, happens if hash different, modulus same?

for example,

hash(key1): 3 hash(key2): 7 hash(key3): 11 hash(key4): 15 

so index 3, these keys different hash , different key go same bucket

i search google hash table implementation, seems don't deal situation. overthought? wrong?

for example, these implementations:

https://gist.github.com/tonious/1377667#file-hash-c-l139

http://www.cs.yale.edu/homes/aspnes/pinewiki/c(2f)hashtables.html?highlight=%28categoryalgorithmnotes%29#ca-552d62422da2c22f8793edef9212910aa5fe0701_156

redis: https://github.com/antirez/redis/blob/unstable/src/dict.c#l488

nginx: https://github.com/nginx/nginx/blob/master/src/core/ngx_hash.c#l34

they compare if key equal

if 2 objects' keys hash same bucket, doesn't matter if it's because have same hash, or because have different hashes both map (via modulo) same bucket. note, collision occurs because of either of these situations commonly dealt placing both objects in bucket-specific list.

when object in hashtable, looking object shares same key. hashing / modulo operation used tell in bucket should look see if object present. once we've found proper bucket, still need compare keys of found objects (i.e., objects in bucket-specific list) directly sure we've found match.

so situation of 2 objects different hashes map same bucket works same reason 2 objects same hashes works: use bucket find candidate matches, , rely on key determine true match.


Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -