Compare Hash table vs. STL map
How is hash table implemented?
For a hashtable, if the number of inputs are small, what can be used instead of a hashtable?
1) map: no need to have a hash function, don't need to handle collision, O (log N) insert and lookup, insert key/data in sorted order. If you need to find a max/min element, use map instead of hash table.
hash table: transforms a key into position within a table. O(1) lookup and insert in most cases, doesn't insert hashed key/data in sorted order
2) You need a good hash function (i.e. % prime #) to ensure the hash values are uniformly distributed. If collision occurs, you use separate chaining method (Good for full table), which is a linked list that chains element in the same slot, or use the probing method, which increases the position by some amount until an empty position is found (good for sparse table)
When the # of elements to table size ratio is greater than a threshold, then the hash table needs to be resized. You need to transfer the entries from old table to new table by recomputing their positions using the new hash function
3) Use a map, which also stores key/data pair, but doesn't need to statically allocate a huge hash table with many empty slots
Jan 17, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment