开发者

Dictionary implementation (Balance Binary Search tree v.s. hash table)

开发者 https://www.devze.com 2023-02-25 04:02 出处:网络
Under what circumstances would it be better to implement a Dictionary ADT using a balanced binary search tree rather than a hash table?

Under what circumstances would it be better to implement a Dictionary ADT using a balanced binary search tree rather than a hash table?

My assumption was that it is always better to use a binary search tree because of its natural orderi开发者_Go百科ng.

But it's true that the hash table's search time can be as good as O(1) , v.s. O(logn) for the binary tree.

so I'm not sure what the circumtaces would be.


Hash tables might have a performance issue when they get filled up and need to reallocate memory (in the context of a hard real-time system).Binary trees don't have this issue. Hash tables need more memory than they actually use, where as binary trees use as much memory as they need.


Your question already contains the answer:

If you don't require any intrinsic ordering then use a hashtable for better performance. If your requirements demand some kind of ordering then consider using a tree.


The time complexity for Dictionary is:

-----------------------------------------
| Operation   |  Dictionary |    BST    | 
-----------------------------------------
| Insert      |  O(1)       | O(log(n)) |
-----------------------------------------
| Delete      |  O(1)       | O(log(n)) |
-----------------------------------------
| Search      |  O(1)       | O(log(n)) |
-----------------------------------------

So where do you use BST vs Dictionary? Here are some main advantages of BST.

  • With BST you always have O(log(n)) operation, but resizing a hash table is a costly operation
  • If you need to get keys in a sorted order you can get them traversing inorder tree. Sorting is not natural to a dictionary
  • Doing statistics, like finding the closest lower and greater element, or range query.
0

精彩评论

暂无评论...
验证码 换一张
取 消