PriorityQueue<TElement, TPriority> · C#
Constructor from items
Builds a queue from many pairs at once with bottom-up heapify.
public PriorityQueue(IEnumerable<(TElement Element, TPriority Priority)> items)
Complexity
| Worst case | O(n) |
|---|---|
| Extra space | O(n) for the array |
Bottom-up heapify sifts down every internal node once; most nodes are near the leaves and sift only a short distance, so the total is O(n), better than n separate O(log n) enqueues.
Tested example
var items = Enumerable.Range(1, 1000).Select(i => (Element: $"job{i}", Priority: 1000 - i));
var queue = new PriorityQueue<string, int>(items); // builds the heap in one O(n) pass
Assert.Equal("job1000", queue.Peek());
// Equal priorities: no FIFO guarantee. Add a sequence number to the priority if order matters.
var fair = new PriorityQueue<string, (int Priority, long Seq)>();
fair.Enqueue("x", (1, 0));
fair.Enqueue("y", (1, 1));
Assert.Equal("x", fair.Dequeue());
Parameters
- items
- The initial pairs.
Behaviour
- Returns
- A new queue.
- Errors and preconditions
- ArgumentNullException if items is null.
- Changes
- Creates the heap.
- Memory and invalidation
- Allocates the array once.