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 case | O(log n) |
|---|---|
| Extra space | O(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
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.