5 data structures-hashtable
Transcript of 5 data structures-hashtable
Hash Table
• A hash table, or a hash map, is a data structure that associates keys with values.
• The primary operation it supports efficiently is a lookup: given a key (e.g. a person's name), find the corresponding value (e.g. that person's telephone number).
• It works by transforming the key using a hash function into a hash, a number that is used as an index in an array to locate the desired location ("bucket") where the values should be.
• It’s possible that the hash function will return the same hash for two different keys. If that happens there will be more than one set of data in a given bucket.
Hash Table
• Unique hash values...
Hash Table
• Duplicate hash values...
Hash Table
• How storing a value works (basically)– I have a key and value I want to store
key = “Kurtz”value = “[email protected]”
– Compute the hash valuehash = function(key)
– Store the key and the valuebucket[hash].add(key, value)
Hash Table
• How retrieving a value works (basically)– I have a key and I want to get the value
key = “Kurtz”
– Compute the hash valuehash = function(key)
– Get the valuebucket[hash].get(key)• If there is only one key/value pair in the bucket, return them.• If there is more than one key/value pair look at each key in the
bucket to find the one that matches our search key and return that pair.