18. Priority Queues and Heaps#
A service desk does not serve tickets in the order they arrived. An outage is handled before a password reset even if the reset came first. A sales dashboard wants the three largest transactions of the day without sorting every amount. Both needs share one abstract operation: remove the item with the next priority. This chapter specifies that operation as a priority queue, implements it with a binary heap stored in an array, and applies it to top-k selection and scheduling. It extends the stacks and queues of Chapter 15, which chose the next item by position, and the trees of Chapter 17, which gave the heap its shape.
Priority queue contract: A rule for which element leaves next, with a stated priority direction, a tie policy, and a defined response to an empty queue. It is not a sorted list.
Binary heap: A complete binary tree in which every parent is no greater than its children. The minimum sits at the root while siblings may be out of order.
Array representation: The complete shape lets an array hold the tree, with children of position i at 2i + 1 and 2i + 2 and the parent at (i - 1) / 2.
Bubble-up and sink-down: Each operation disturbs only one root-to-leaf path, so repair takes work proportional to the heap height rather than to the number of items.
Top-k selection: A min-heap holding only the k best values so far exposes the weakest retained value at its root, which is exactly the boundary a new candidate must beat.
Section 18.1 states the priority contract with C#’s PriorityQueue, makes ties deterministic with an (urgency, arrival) priority, and draws the implicit tree behind a heap array. Section 18.2 implements a generic BinaryMinHeap with enqueue, dequeue, peek, and an invariant check, tracing each swap and stating each operation’s cost. Section 18.3 keeps the largest k amounts from a stream, explains why that invariant holds, and separates priority from fairness when urgent work never stops arriving. Coordinating a heap with a dictionary for cancellation waits until hash collections are introduced in Chapter 19.
Chapter Video
Data Structures - Full Course for Beginners (3:11:08) by Tech With Tim.
Hosted on YouTube; property of its original creator, embedded here for educational reference only.
This is a full course, not a required single viewing. Use its topic navigation to review this chapter’s concepts; the reading sequence below defines the chapter scope.
Learning Objectives
By the end of this chapter, you will be able to:
State a priority queue’s removal contract, including priority direction, tie policy, and empty-queue behavior, and explain why it is weaker than a fully sorted sequence.
Use PriorityQueue<TElement, TPriority> with Enqueue, Dequeue, and TryDequeue, and make equal urgencies leave in arrival order by using an (urgency, arrival) tuple as the priority.
Draw the complete binary tree encoded by a heap array, compute parent and child indexes from a position, and check the min-heap order rule at every parent while distinguishing Count from capacity.
Trace enqueue with bubble-up and dequeue with sink-down on small arrays, including singleton and empty cases, and explain why repairing one root-to-leaf path is sufficient.
Implement a generic BinaryMinHeap
with Enqueue, Peek, Dequeue, TryDequeue, and an IsValid check, and state the cost of each operation, including the effect of backing-list growth. Keep the k largest values from a stream using a min-heap of at most k entries, state the invariant that justifies each replacement, and bound the maintenance work as O(n log(k + 1)), and compare streaming storage with batch heap selection.
Explain why priority is not fairness, describe how starvation arises under strict priority, and name a scheduling policy such as aging that addresses it.
Chapter Flow
Assignments contains the preview, connected lab, and homework.
Glossary
# |
Term |
Explanation |
|---|---|---|
1 |
Priority queue |
An abstract data type that removes the item with the next priority rather than the oldest item. |
2 |
Priority |
A value that decides removal order; in the library queue and this chapter, lower values leave first. |
3 |
Removal contract |
The promise about which item Dequeue returns; it says nothing about the order of stored items. |
4 |
Tie policy |
The rule that decides between items with equal priority, such as arrival order. |
5 |
Arrival number |
A unique counter paired with urgency so the tuple (urgency, arrival) makes ties deterministic. |
6 |
TryDequeue |
A library method that reports false on an empty queue instead of throwing an exception. |
7 |
Heap |
A tree-shaped representation of a priority queue that keeps the next item at the root. |
8 |
Min-heap |
A heap in which each parent’s priority is less than or equal to its children’s, so the root is a minimum. |
9 |
Max-heap |
A heap in which each parent is greater than or equal to its children, so the root is a maximum. |
10 |
Shape rule |
The heap tree is complete: filled level by level from left to right with no gaps. |
11 |
Order rule |
Every parent compares no worse than its children; siblings need not be ordered. |
12 |
Complete binary tree |
A binary tree whose levels are full except possibly the last, which fills from the left. |
13 |
Implicit tree |
The tree encoded by array positions alone, with no node objects or child references stored. |
14 |
Parent index |
For a non-root position i, the position (i - 1) / 2 using integer division. |
15 |
Child indexes |
For position i, the positions 2i + 1 and 2i + 2, valid only when less than Count. |
16 |
Count versus capacity |
Count is the number of live heap entries; capacity is the size of the backing storage. |
17 |
Bubble up |
After appending a new item at the end, swap it with its parent while it is smaller; also called sift up. |
18 |
Sink down |
After moving the last item to the root, swap it with its smaller child while a child is smaller; also called sift down. |
19 |
Smaller child |
The child a sink-down step must choose so the other child is never left above a larger parent. |
20 |
Peek |
Return the root item without removing it; throws on an empty heap. |
21 |
Invariant check |
A diagnostic scan of every parent-child pair that confirms the order rule; it costs linear time. |
22 |
Heap height |
The number of levels below the root, logarithmic in the live size for a complete tree. |
23 |
Amortized cost |
The average cost per operation over a long sequence, which absorbs occasional backing-array growth. |
24 |
Bottom-up construction |
Building a heap from an array by sinking internal nodes from right to left in linear total work. |
25 |
Top-k selection |
Keeping only the k best values seen so far, using a heap whose root is the weakest retained value. |
26 |
Retained set |
The values currently kept by a top-k process; after each input it holds the best min(k, seen) values. |
27 |
Starvation |
A low-priority item that is never served because higher-priority work keeps arriving. |
28 |
Fairness |
A scheduling requirement beyond priority order, such as bounded waiting for every request. |
29 |
Aging |
A policy that raises an item’s priority the longer it waits, preventing starvation. |
30 |
d-ary heap |
A heap in which each parent has up to d children; the .NET library queue uses four internally. |
31 |
Captured priority |
The priority value supplied when an entry is enqueued, which does not automatically follow later element changes. |