PriorityQueue<TElement, TPriority> · C#

Dequeue / TryDequeue

Removes and returns the element with the smallest priority.

public TElement Dequeue(); public bool TryDequeue(out TElement element, out TPriority priority)

Complexity

Worst caseO(log n)
Extra spaceO(1)

Take the root, move the last element to the root, then sift it down by swapping with its smallest child (up to four children compared per level).

Tested example

var queue = new PriorityQueue<string, int>([("c", 3), ("a", 1), ("b", 2)]);
Assert.Equal("a", queue.Dequeue());
Assert.True(queue.TryDequeue(out string? next, out int priority));
Assert.Equal(("b", 2), (next, priority));
queue.Dequeue();
Assert.Throws<InvalidOperationException>(() => queue.Dequeue()); // empty
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/PriorityQueueExamples.cs

Behaviour

Returns
The element (and its priority with TryDequeue).
Errors and preconditions
Dequeue: InvalidOperationException if the queue is empty.
Changes
Count decreases by 1.
Memory and invalidation
No allocation.