Hash Table
see data structure
a map implemented using a hash function
aka hash map
time computational complexity:
| Average | Worst | |
|---|---|---|
| Insert | O ->1 |
O (*) |
| Remove | O ->1 |
O (*) |
| Lookup | O ->1 |
O (*) |
note time computational complexity is
O ->1only if the hash function is uniform
definition the load factor of a hash table is the ratio of the number of elements in the hash table to the number of slots in the hash table
definition the maximum load factor aa of a hash table load factor allowed before the hash table is resized
Operations (Separate Chaining)
let a list of n buckets (such as a list, a tree, a set, etc.) be used to store keys and values
procedure computing the hash of a key
given a key
kand a hash functionH,
- return
"mod" n (H k)
procedure inserting into a hash table
given a key
kand a valuev,
- compute the hash
hofk- insert (or update)
k, vinto the bucket at indexhin the list- resize the hash table
procedure removing from a hash table
given a key
k,
- compute the hash
hofk- remove
k, vfrom the bucket at indexhin the list- resize the hash table
procedure looking up a value in a hash table
given a key
k,
- compute the hash
hofk- look up
kin the bucket at indexhin the list- resize the hash table
Operations (Open Addressing)
see math notation
let a list of n elements be used to store keys and values
let a probing function P be used to find the next element to probe. typically, P has a probing › cycle length of n.
definition a tombstone is a unique marker used to indicate that a key has been removed from a hash table.
procedure computing the hash of a key
given a key
kand a hash functionH,
- return
"mod" n (H k)
procedure computing
ith value in a probing sequencegiven a probing sequence index
iand a keyk:
- return
"mod" n (H k : P i k)
procedure inserting into a hash table
given a key
kand a valuev,
- compute the hash
hofk- if index
hof the list is empty or is a tombstone, insert (or update)k, vinto indexhof the list. otherwise, sethto the next value in its probing sequence and repeat this step- resize the hash table
procedure removing from a hash table
given a key
k,
- compute the hash
hofk- if index
hof the list containsk, removek, vfrom indexhof the list by replacing it with a tombstone. otherwise, sethto the next value in its probing sequence and repeat this step- resize the hash table
procedure looking up a value in a hash table
given a key
k,
- compute the hash
hofk- if index
hof the list containsk, return the value associated withk. if indexhof the list is empty, the element is not present in the hash table, break. otherwise, sethto the next value in its probing sequence and repeat this step- resize the hash table
note if tomstones are encountered during the search, key
kcan be moved to the first tombstone encountered for faster future lookups. this technique is called lazy deletion or lazy relocation