How to implement a dynamic-size hash table?

北城以北 提交于 2019-12-21 10:20:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9858751/how-to-implement-a-dynamic-size-hash-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!