Heap

Intro

A heap is an implicit complete d ary tree that keeps a priority rule between parent and child nodes. In a min heap, the smallest value is always at the root, so extracting the next priority item stays fast. In .NET, PriorityQueue<TElement, TPriority> is implemented as an array backed quaternary heap that gives fast enqueue and dequeue for scheduler and path finding workloads.

How It Works

Heaps are not globally sorted like a list. They only guarantee local ordering between parent and children, which is enough to keep the best candidate at the top.

Structure

graph TD
    A[one root value one]
    A --> B[two child value three]
    A --> C[three child value five]
    B --> D[four child value eight]
    B --> E[five child value nine]
    C --> F[six child value six]
    C --> G[seven child value seven]

Example

var pq = new PriorityQueue<string, int>();

pq.Enqueue("critical", 1);
pq.Enqueue("normal", 5);
pq.Enqueue("high", 2);

Console.WriteLine(pq.Dequeue()); // critical
Console.WriteLine(pq.Peek());    // high

Pitfalls

Tradeoffs

Choice Heap Alternative Decision criteria
Repeated best-item extraction PriorityQueue O(log n) per op Sorted list O(n) insert Heap wins for incremental arrivals. Sorted list is simpler when all data is known upfront and you need ordered iteration.
Ordered iteration Not suitable SortedSet<T> Use SortedSet when you need both priority extraction and in-order traversal.

Questions


Whats next