How does a hash table work?

后端 未结 15 2290
盖世英雄少女心
盖世英雄少女心 2020-11-22 09:32

I\'m looking for an explanation of how a hash table works - in plain English for a simpleton like me!

For example, I know it takes the key, calculates the hash (I a

15条回答
  •  执笔经年
    2020-11-22 10:19

    For all those looking for programming parlance, here is how it works. Internal implementation of advanced hashtables has many intricacies and optimisations for storage allocation/deallocation and search, but top-level idea will be very much the same.

    (void) addValue : (object) value
    {
       int bucket = calculate_bucket_from_val(value);
       if (bucket) 
       {
           //do nothing, just overwrite
       }
       else   //create bucket
       {
          create_extra_space_for_bucket();
       }
       put_value_into_bucket(bucket,value);
    }
    
    (bool) exists : (object) value
    {
       int bucket = calculate_bucket_from_val(value);
       return bucket;
    }
    

    where calculate_bucket_from_val() is the hashing function where all the uniqueness magic must happen.

    The rule of thumb is: For a given value to be inserted, bucket must be UNIQUE & DERIVABLE FROM THE VALUE that it is supposed to STORE.

    Bucket is any space where the values are stored - for here I have kept it int as an array index, but it maybe a memory location as well.

提交回复
热议问题