-2

is there a data structure in c# that represent heap in c# if not then what is the best data structure to use to find the minimum element in efficiently time and allow Repetition of elements thank in advance

1 Answers1

4

The minimum element can be retrieved in O(1) by storing items sorted. You will then take the first item out of the list. This might (not if you are adding an element to the last index) sacrifice performance for insertion though.

To get it in O(1) you will have to use a linear search algorithm but still store the values sorted. On a List that would be List[0].

In C# you can accomplish fast retrievals by using a Sorted Collection.

However, the Sorted Collection uses binary search to retrieve items, resulting in O(log n), even if the smallest element is at position 1.

Another alternative is to use the Sorted Set. There you will have to write your own IComparer, you can read about it here. To allow it to store duplicate values.

I recommend you to have a read over here as well.

Community
  • 1
  • 1
Emz
  • 1,280
  • 1
  • 14
  • 26
  • Why can the minimum element be retrieved in `O(1)` when a self-balancing binary search tree is actually used in the mentioned `SortedCollection` classes? Or did I get something wrong? –  Dec 17 '15 at 22:15
  • I should clarify that. Thanks for pointing that out. – Emz Dec 17 '15 at 22:15
  • 1
    What's wrong with the SortedSet class? Just out of curiousity. Does it not allow duplicates? – ScoobyDrew18 Dec 17 '15 at 22:19
  • Just as a side note: http://stackoverflow.com/questions/102398/priority-queue-in-net conquers this very issue, and maybe has some resources that allow duplicates ... –  Dec 17 '15 at 22:23
  • @ScoobyDrew18, updated with that now, it completely eluded my mind when I answered. – Emz Dec 17 '15 at 22:29