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 caseO(1)
Worst caseO(log n)
Extra spaceO(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());
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/PriorityQueueExamples.cs

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.