C# · Priority queue · container

PriorityQueue<TElement, TPriority>

A min-priority queue: elements with the smallest priority come out first; O(log n) enqueue and dequeue.

using System.Collections.Generic; // .NET 6+
public class PriorityQueue<TElement, TPriority>

.NET 6+ (shown on .NET 10)

Operations

OperationTimeWorst caseChanges the collection
EnqueueO(log n)O(log n)Yes
Dequeue / TryDequeueO(log n)O(log n)Yes
Peek / TryPeekO(1)O(1)No
Constructor from itemsO(n)O(n)Yes

"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.

How it works

Representation
An array-backed quaternary (4-ary) min-heap of (element, priority) pairs, as documented.
Ordering
Dequeue order is by ascending priority. Equal priorities come out in no guaranteed order, and enumeration (UnorderedItems) is in heap-array order.
Duplicates
Allowed, for both elements and priorities.
Mutability
Mutable. There is no way to change the priority of an element already in the queue (remove and re-add, or use a lazy-deletion pattern).
Memory and ownership
One array slot per pair; grows like List<T>.
Equality and comparison
Priorities are compared with IComparer<TPriority> (Comparer<TPriority>.Default unless you pass one). Elements are never compared. Pass a reversed comparer for a max-queue.

Pitfalls

  • Not stable: equal priorities are not FIFO. Add a sequence number to the priority if order matters.
  • Enumerating UnorderedItems does not give priority order.
  • There is no decrease-key; Dijkstra-style code usually enqueues duplicates and skips stale entries when dequeued.

Alternatives

  • SortedSet<(TPriority, long, TElement)> when you need removal of arbitrary items in O(log n)
  • Queue<T> when every priority is equal

In other languages

References