Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dictionary instead of sorting and then searching

I was studying hash tables and a thought came:

Why not use dictionaries for searching an element instead of first sorting the list then doing binary search? (assume that I want to search multiple times)

  1. We can convert a list to a dictionary in O(n) (I think) time because we have to go through all the elements.
  2. We add all those elements to dictionary and this takes O(1) time
  3. When the dictionary is ready,we can then search for any element in O(1) time(average) and O(n) is the worst case

Now if we talk about average case O(n) is better than other sorting algorithms because at best they take O(nlogn).And if I am right about all of what I have said then why not do this way?

I know there are various other things which you can do with the sorted elements which cannot be done in an unsorted dictionary or array.But if we stick only to search then Is it not a better way to do search than other sorting algorithms?

like image 826
sid597 Avatar asked Nov 25 '25 22:11

sid597


1 Answers

Right, a well-designed hash table can beat sorting and searching.

For a proper choice, there are many factors entering into play such as in-place requirement, dynamism of the data set, number of searches vs. insertions/deletions, ease to build an effective hashing function...