I am looking for a .NET implementation of a priority queue or heap data structure
Priority queues are data structures that provide more flexibility than simple sorting, because they allow new elements to enter a system at arbitrary intervals. It is much more cost-effective to insert a new job into a priority queue than to re-sort everything on each such arrival.
The basic priority queue supports three primary operations:
- Insert(Q,x). Given an item x with key k, insert it into the priority queue Q.
- Find-Minimum(Q). Return a pointer to the item whose key value is smaller than any other key in the priority queue Q.
- Delete-Minimum(Q). Remove the item from the priority queue Q whose key is minimum
Unless I am looking in the wrong place, there isn't one in the framework. Is anyone aware of a good one, or should I roll my own?
As mentioned in Microsoft Collections for .NET, Microsoft has written (and shared online) 2 internal PriorityQueue classes within the .NET Framework. Their code is available to try out.
EDIT: As @mathusum-mut commented, there is a bug in one of Microsoft's internal PriorityQueue classes (the SO community has, of course, provided fixes for it): Bug in Microsoft's internal PriorityQueue<T>?
Here's my attempt at a .NET heap
Some tests:
Here is the another implementation from NGenerics team:
NGenerics PriorityQueue
You might like IntervalHeap from the C5 Generic Collection Library. To quote the user guide
The API is simple enough
Install from Nuget https://www.nuget.org/packages/C5 or GitHub https://github.com/sestoft/C5/
I had the same issue recently and ended up creating a NuGet package for this.
This implements a standard heap-based priority queue. It also has all the usual niceties of the BCL collections:
ICollection<T>
andIReadOnlyCollection<T>
implementation, customIComparer<T>
support, ability to specify an initial capacity, and aDebuggerTypeProxy
to make the collection easier to work with in the debugger.There is also an Inline version of the package which just installs a single .cs file into your project (useful if you want to avoid taking externally-visible dependencies).
More information is available on the github page.
You may find useful this implementation: http://www.codeproject.com/Articles/126751/Priority-queue-in-Csharp-with-help-of-heap-data-st.aspx
it is generic and based on heap data structure