Min Heap Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Min Heap runs in O(log n) time and O(n) space, in C# as in every other language.
- ✓PriorityQueue<TElement, TPriority> was added in .NET 6 and is a min-heap: Dequeue returns the element with the LOWEST priority value.
- ✓Use the (element, priority) pair rather than encoding priority into the element. Prefer TryDequeue and TryPeek over Dequeue/Peek, which throw on an empty queue.
- ✓The C# trap: PriorityQueue is explicitly NOT stable: two elements with equal priority come out in an unspecified order, so an "insertion order preserved within a priority" assumption will hold in testing and break in production.
- ✓Backed by a growable array of (TElement, TPriority) pairs. With struct priorities such as int the pairs live inline, so there is no boxing and the layout is cache-friendly, this is meaningfully faster than the pre-.NET 6 SortedSet workaround, which allocated a tree node per element.
What Min Heap actually is
Min Heap in C#: what you actually reach for
C# implementation
using System;
using System.Collections.Generic;
// .NET 6+. Min-heap: lowest priority value dequeues first.
var queue = new PriorityQueue<string, int>();
queue.Enqueue("b", 5);
queue.Enqueue("a", 1);
queue.Enqueue("c", 8);
Console.WriteLine(queue.Dequeue()); // "a"
// TryDequeue: Dequeue THROWS on empty.
while (queue.TryDequeue(out var item, out var priority))
Console.WriteLine($"{item} @ {priority}");
// NOT stable. For deterministic ties, make the priority a tuple with a
// monotonic sequence number:
var stable = new PriorityQueue<string, (int Cost, long Seq)>();
long seq = 0;
stable.Enqueue("x", (5, seq++));
stable.Enqueue("y", (5, seq++)); // dequeues after "x", guaranteed
// Bulk load:
var bulk = new PriorityQueue<int, int>(initialCapacity: 1024);
bulk.EnqueueRange(new[] { (3, 3), (1, 1), (2, 2) });Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Min Heap?
PriorityQueue<TElement, TPriority> was added in .NET 6 and is a min-heap: Dequeue returns the element with the LOWEST priority value. It separates the element from its priority, which is cleaner than the comparator-over-elements design elsewhere. Before .NET 6 there was nothing, which is why so much older C# code uses SortedSet or SortedList as a stand-in.
What is the most common C# mistake when implementing Min Heap?
PriorityQueue is explicitly NOT stable: two elements with equal priority come out in an unspecified order, so an "insertion order preserved within a priority" assumption will hold in testing and break in production. Add a monotonic sequence number to the priority (a tuple priority with a comparer) if you need stability. There is also no way to update an element's priority, no decrease-key, so Dijkstra in C# uses the lazy-deletion pattern of enqueuing duplicates and skipping stale pops.
How does Min Heap actually perform in C#?
Backed by a growable array of (TElement, TPriority) pairs. With struct priorities such as int the pairs live inline, so there is no boxing and the layout is cache-friendly, this is meaningfully faster than the pre-.NET 6 SortedSet workaround, which allocated a tree node per element. Supplying a custom IComparer adds an interface dispatch per comparison; the default comparer for primitives is devirtualised by the JIT. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.