Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a dynamic-size hash table?

I know the basic principle of the hash table data structure. If I have a hash table of size N, I have to distribute my data into these N buckets as evenly as possible.

But in reality, most languages have their built-in hash table types. When I use them, I don't need to know the size of hash table beforehand. I just put anything I want into it. For example, in Ruby:

h = {}
10000000.times{ |i| h[i]=rand(10000) }

How can it do this?

like image 354
Lai Yu-Hsuan Avatar asked Mar 25 '12 08:03

Lai Yu-Hsuan


People also ask

What is dynamic hash table?

In computer science, dynamic perfect hashing is a programming technique for resolving collisions in a hash table data structure. While more memory-intensive than its hash table counterparts, this technique is useful for situations where fast queries, insertions, and deletions must be made on a large set of elements.

Is a hash table a dynamic data structure?

Dynamic data structures allow lookups and change based on their use: in hash tables and B-trees there can be additions and deletions. Another form of dynamic data structure in a union-find tree.

How do I resize a hash table?

Resizing a hash table consists of choosing a new hash function to map to the new size, creating a hash table of the new size, iterating through the elements of the old table, and inserting them into the new table. .

What happens when you vary the size of a hash table?

Changing the size of the hash table will change the compression function hence leading to the keys being allotted to different buckets.


1 Answers

See the Dynamic resizing section of the Hash table article on Wikipedia.

The usual approach is to use the same logic as a dynamic array: have some number of buckets and when there is too much items in the hash table, create a new hash table with a larger size and move all the items to the new hash table.

Also, depending on the type of hash table, this resizing might not be necessary for correctness (i.e. it would still work even without resizing), but it is certainly necessary for performance.

like image 104
svick Avatar answered Oct 25 '22 01:10

svick