Data Structures and Algorithms • C# examples
Binary Heaps and Priority Queues
Maintain access to the highest- or lowest-priority item in a nearly complete tree.
Concept
A binary heap stores a complete binary tree in an array. A min-heap keeps each parent no greater than its children; a max-heap reverses the order. The root is easy to access, while arbitrary search is not. Priority queues use heaps to schedule the next item efficiently.
How to approach it
Sift up after insertion and sift down after removing the root; build a heap bottom-up in linear time.
Complexity
Peek O(1), insert/remove O(log n), build O(n).
C# example
var ready = new PriorityQueue<string, int>();
ready.Enqueue("urgent", 1);
ready.Enqueue("normal", 5);
Console.WriteLine(ready.Dequeue());
Expected result or behavior
The smallest priority value is dequeued first by the default ordering.
Practice exercise
Use a priority queue to process jobs by deadline and define tie behavior.
Key takeaway: A heap is partially ordered to make extremal access fast, not to support arbitrary lookup.