6.9 Binary Heaps, Floyd's Build-Heap & Heapsort
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy:β
Picture a military command hierarchy standing on a parade grid. The top General always stands at slot 0 in front; directly behind are two Colonels, behind each Colonel stand two Captains, and so on down to privates. Every officer outranks every soldier in their subtree, so promoting or dismissing the General takes just local chain-of-command swaps β yet two Colonels on the same row never bother comparing ranks with each other!
π» Bridging to Computer Science:β
Self-balancing BSTs maintain total sorted order at the cost of of left/right child pointers per node and cache misses. A Binary Heap maintains only partial root-dominance order inside a Complete Binary Tree packed contiguously inside a raw array with zero child pointers β giving extremal access, push/pop, and batch construction.
πTable of Contents
- π§± Complete Binary Tree Array Arithmetic & Zero-Pointer Layout
- βοΈ Sift-Up (
insert), Sift-Down (extractMax), and Delete Discipline - β‘ Floyd's Bottom-Up buildHeap Linear-Time Proof
- π Heapsort & Extremal Order Theorems
- π Real-World Production Context: Timers, Pathfinding & Streaming Heaps
- π Numerical Applications & Worked Examples
- π― Exam & Interview Pitfall Check
- π Navigation & Next Steps
π§± Complete Binary Tree Array Arithmetic & Zero-Pointer Layoutβ
Because every level of a Complete Binary Tree (CBT) fills tightly left-to-right with zero structural gaps, pointers disappear completely and become pure bit-shifts / index arithmetic:
For 0-based indexing ():
- Left Child:
- Right Child:
- Parent: (for )
- Node Level (Root = Level 0):
(In 1-based pseudocode such as CLRS, children simplify to and , parent to , and leaves span .)
βοΈ Sift-Up (insert), Sift-Down (extractMax), and Delete Disciplineβ
Notice a core structural rule of heaps: Heap deletion is always executed at the Root () β arbitrary mid-array deletions require tracking handles separately.
insert(key)via Sift-Up β : Appendkeyto the very end (A[n] = key) to preserve CBT completeness, then swap upward withparent(i)whenever the heap property is violated.extractMax()via Sift-Down (heapifyDown) β :- Save root
max = A[0]. - Overwrite root with the very last leaf
A[0] = A[n - 1]and shrinkn--(zero structural gap created!). - Compare
A[i]with its left & right children; swap downward with the larger child until heap-order stabilizes.
- Save root
β‘ Floyd's Bottom-Up buildHeap Linear-Time Proofβ
Building a heap from unsorted elements has two dramatically different strategies:
- Top-Down Repeated Insert (): Inserting elements one-by-one from root downward pushes the deepest leaves up levels, costing work.
- Floyd's Bottom-Up
buildHeap(): Leaves (floor(n/2) .. n-1) already have subtree height and trivially satisfy the heap property! Walking backwards from the last internal nodei = floor(n/2) - 1down to0, callingsiftDown(i)makes most nodes settle in , , or swaps!
The exact comparison sum bounds the total work across all heights :
π Heapsort & Extremal Order Theoremsβ
In-Place Heapsort executes two clean phases inside the same array (maxHeap):
- Run Floyd's
buildMaxHeap(A, n)in time. - Repeat times: swap the maximum root
A[0]with the tail elementA[i], shrink the heap boundary by , and restore heap order viasiftDown(0)in .
- Time Complexity: across Best, Average, and Worst cases.
- Space Complexity: strictly in-place (with iterative
siftDown). - Stability: Unstable β long-range root-to-tail swaps reorder equal keys arbitrarily.
Critical Extremal & Conversion Theoremsβ
- Finding Minimum in a Max-Heap (or Max in Min-Heap): Since internal nodes dominate their descendants, the minimum element must sit inside the leaf range , where keys have zero mutual ordering β scanning all leaves takes !
- Finding 2nd Largest in a Distinct Max-Heap: Strictly one of the Root's two children ( or ) β solvable in comparisons!
- Converting BST Max-Heap vs. Max-Heap BST:
- BST Max-Heap takes : Run reverse Inorder (
R -> N -> L) into a contiguous array descending sorted array[90, 80, 70, ...]ALREADY satisfies the Max-Heap property ()! - Max-Heap BST requires : If converting an arbitrary Max-Heap into a BST took , then building a heap in + converting + Inorder reading would break the comparison sorting lower bound !
- BST Max-Heap takes : Run reverse Inorder (
π Real-World Production Context: Timers, Pathfinding & Streaming Heapsβ
Priority Queues & Heaps in Real Systems
Contiguous cache locality makes Binary Heaps the default priority queue engine across software stacks
Dijkstra & A* Pathfinding
Routing / Game AI- Min-Heaps repeatedly extract the nearest unexplored vertex in O(log V) time.
- Powers GPS navigation engines, packet schedulers, and robotics motion planners.
Kernel Timers & Event Loops
OS / Node.js libuv / Go- Go runtime network poller and Node.js libuv track upcoming timeouts in an array-backed Min-Heap.
- Peeking next expiration timestamp takes O(1) without touching idle sockets.
Streaming Top-K & Running Median
Analytics Telemetry- Size-K Min-Heap extracts the top K largest elements out of billions of events in O(N log K) RAM-lite time.
- Paired Max-Heap + Min-Heap computes live streaming medians in O(log N) per event.
Linux Introsort Safety Fallback
std::sort Fallback- When Quicksort recursion depth exceeds 2 * log2(n), C++ std::sort switches immediately to Heapsort.
- Guarantees strict O(n log n) worst-case runtime while staying O(1) in-place.
π Numerical Applications & Worked Examplesβ
Consider the unsorted 0-indexed array ():
- Which element index is the last internal node where Floyd's
buildMaxHeapbeginssiftDown? - Trace Floyd's
buildMaxHeap(A)step by step to produce the final Max-Heap array. - After calling
extractMax()twice on your built Max-Heap, what sits at index0and what are the remaining heap leaf values?
Step-by-Step Solution:β
-
Last Internal Node Index: (Nodes at indices
3, 4, 5, 6are already trivial 1-node leaf heaps.) -
Floyd's Bottom-Up Trace (
i = 2down to0):i = 2(10): Children[5]=50, [6]=15. Larger child is50. Swap10 <-> 50.i = 1(25): Children[3]=40, [4]=35. Larger child is40. Swap25 <-> 40.i = 0(12): Children[1]=40, [2]=50. Larger child is50([2]). Swap12 <-> 50, then sift12down against children[5]=10, [6]=15swap12 <-> 15([6]).- Built Max-Heap Array:
[50, 40, 15, 25, 35, 10, 12].
-
Two
extractMax()Operations:- 1st Pop (
50): Move12to root . Sift12down (12 <-> 40, then12 <-> 35) . - 2nd Pop (
40): Move10to root . Sift10down (10 <-> 35, then10 <-> 25) . - New Root:
35([0]). Remaining leaves ():[15, 10, 12].
- 1st Pop (
π― Exam & Interview Pitfall Checkβ
- Can a heap simultaneously store identical elements (duplicates)?
- Yes! Heap order enforces (or ), not strict inequality, so duplicate priorities work effortlessly.
- How many elements in an array of size are leaves of a Complete Binary Tree?
- leaves sitting at indices , leaving exactly internal nodes!
- In a Min-Heap of distinct integers, which indices can potentially hold the maximum key?
- Any of the leaf positions (
floor(n/2) .. n-1) β finding it takes comparisons.
- Any of the leaf positions (
- Claiming
buildHeapTakes Time: Top-down construction (npushes) IS , whereas Floyd's bottom-upsiftDownvisits half the array at height 0 (cost 0), a quarter at height 1, shrinking geometrically to strictly ! - Assuming Arbitrary Search / Delete in a Heap Is : Without maintaining an external hash-map tracking every key's live array index, locating an arbitrary element inside a heap costs linear search! Only Root extract/peek have fast / bounds.
- Confusing Ascending Order With Min-Heap vs. Max-Heap in Heapsort: To sort an array ascending in-place (
[1, 2, ..., n]), you build a Max-Heap (not a Min-Heap!), because each pop moves the largest root into the back end of the array!
π Navigation & Next Stepsβ
Next, we step from binary heaps into high-fan-out disk storage trees: B-Trees and B+ Trees Foundations for RDBMS indexes and filesystems.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.