1

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 ordering.

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.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Glara
  • 11
  • 1
  • 2

3 Answers3

1

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.

titus
  • 5,512
  • 7
  • 25
  • 39
0

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.
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
0

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.

LukeH
  • 263,068
  • 57
  • 365
  • 409