PriorityQueue<TElement, TPriority> · C#
Enqueue
Adds an element with a priority and restores the heap order by sifting up.
public void Enqueue(TElement element, TPriority priority)
Complexity
| Best case | O(1) |
|---|---|
| Worst case | O(log n) |
| Extra space | O(1) amortized |
Append at the end of the array, then swap with the parent while the parent has a larger priority. A 4-ary heap has height log₄ n.
Tested example
var tasks = new PriorityQueue<string, int>();
tasks.Enqueue("write tests", 2);
tasks.Enqueue("fix outage", 0); // smaller priority value = served first (min-heap)
tasks.Enqueue("refactor", 5);
Assert.Equal(3, tasks.Count);
Assert.Equal("fix outage", tasks.Peek());
Parameters
- element
- The payload.
- priority
- Smaller values are served first (with the default comparer).
Behaviour
- Returns
- Nothing.
- Errors and preconditions
- None in normal use.
- Changes
- Count increases by 1.
- Memory and invalidation
- May grow the array.