Skip to main content

6.9 Binary Heaps, Floyd's Build-Heap & Heapsort

πŸ“šModule 06 β€’ Trees & HierarchiesTopic 6.9⏱️15 min read
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ 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 16Β bytes16\text{ bytes} 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 O(1)\mathcal{O}(1) extremal access, O(log⁑n)\mathcal{O}(\log n) push/pop, and Θ(n)\Theta(n) batch construction.


🧱 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 (i∈{0,…,nβˆ’1}i \in \{0, \dots, n - 1\}):

  • Left Child: 2i+12i + 1
  • Right Child: 2i+22i + 2
  • Parent: ⌊(iβˆ’1)/2βŒ‹\lfloor (i - 1) / 2 \rfloor (for i>0i > 0)
  • Node Level (Root = Level 0): ⌊log⁑2(i+1)βŒ‹\lfloor \log_2(i + 1) \rfloor

(In 1-based pseudocode such as CLRS, children simplify to 2i2i and 2i+12i + 1, parent to ⌊i/2βŒ‹\lfloor i / 2 \rfloor, and leaves span ⌊n/2βŒ‹+1…n\lfloor n/2 \rfloor + 1 \dots n.)


βš™οΈ Sift-Up (insert), Sift-Down (extractMax), and Delete Discipline​

Notice a core structural rule of heaps: Heap deletion is always executed at the Root (A[0]A[0]) β€” arbitrary mid-array deletions require tracking handles separately.

  1. insert(key) via Sift-Up β€” O(log⁑n)\mathcal{O}(\log n): Append key to the very end (A[n] = key) to preserve CBT completeness, then swap upward with parent(i) whenever the heap property is violated.
  2. extractMax() via Sift-Down (heapifyDown) β€” O(log⁑n)\mathcal{O}(\log n):
    • Save root max = A[0].
    • Overwrite root with the very last leaf A[0] = A[n - 1] and shrink n-- (zero structural gap created!).
    • Compare A[i] with its left & right children; swap downward with the larger child until heap-order stabilizes.

⚑ Floyd's Bottom-Up buildHeap Linear-Time Proof​

Building a heap from nn unsorted elements has two dramatically different strategies:

  • Top-Down Repeated Insert (O(nlog⁑n)\mathcal{O}(n \log n)): Inserting nn elements one-by-one from root downward pushes the n/2n/2 deepest leaves up β‰ˆlog⁑n\approx \log n levels, costing Θ(nlog⁑n)\Theta(n \log n) work.
  • Floyd's Bottom-Up buildHeap (Θ(n)\Theta(n)): Leaves (floor(n/2) .. n-1) already have subtree height 00 and trivially satisfy the heap property! Walking backwards from the last internal node i = floor(n/2) - 1 down to 0, calling siftDown(i) makes most nodes settle in 00, 11, or 22 swaps!

The exact comparison sum bounds the total work across all heights h=0β€¦βŒŠlog⁑2nβŒ‹h = 0 \dots \lfloor \log_2 n \rfloor:

T(n)β‰€βˆ‘h=0⌊log⁑2nβŒ‹βŒˆn2h+1βŒ‰β‹…cβ‹…h≀cn2βˆ‘h=0∞h2h=cn2β‹…2=Θ(n)T(n) \le \sum_{h=0}^{\lfloor \log_2 n \rfloor} \left\lceil \frac{n}{2^{h+1}} \right\rceil \cdot c \cdot h \le \frac{cn}{2} \sum_{h=0}^{\infty} \frac{h}{2^{h}} = \frac{cn}{2} \cdot 2 = \mathbf{\Theta(n)}

πŸ† Heapsort & Extremal Order Theorems​

In-Place Heapsort executes two clean phases inside the same array (maxHeap):

  1. Run Floyd's buildMaxHeap(A, n) in Θ(n)\Theta(n) time.
  2. Repeat nβˆ’1n - 1 times: swap the maximum root A[0] with the tail element A[i], shrink the heap boundary by 11, and restore heap order via siftDown(0) in O(log⁑n)\mathcal{O}(\log n).
  • Time Complexity: Θ(nlog⁑n)\Theta(n \log n) across Best, Average, and Worst cases.
  • Space Complexity: O(1)\mathcal{O}(1) 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 ⌊n/2βŒ‹β€¦nβˆ’1\lfloor n/2 \rfloor \dots n - 1, where keys have zero mutual ordering β€” scanning all ⌈n/2βŒ‰\lceil n/2 \rceil leaves takes Θ(n)\Theta(n)!
  • Finding 2nd Largest in a Distinct Max-Heap: Strictly one of the Root's two children (A[1]A[1] or A[2]A[2]) β€” solvable in O(1)\mathcal{O}(1) comparisons!
  • Converting BST β†’\to Max-Heap vs. Max-Heap β†’\to BST:
    • BST β†’\to Max-Heap takes Θ(n)\Theta(n): Run reverse Inorder (R -> N -> L) into a contiguous array β€…β€ŠβŸΉβ€…β€Š\implies descending sorted array [90, 80, 70, ...] ALREADY satisfies the Max-Heap property (A[⌊(iβˆ’1)/2βŒ‹]β‰₯A[i]A[\lfloor (i-1)/2 \rfloor] \ge A[i])!
    • Max-Heap β†’\to BST requires Ξ©(nlog⁑n)\Omega(n \log n): If converting an arbitrary Max-Heap into a BST took o(nlog⁑n)o(n \log n), then building a heap in Θ(n)\Theta(n) + converting + Inorder reading would break the comparison sorting lower bound Ξ©(nlog⁑n)\Omega(n \log n)!

🏭 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​

πŸ“Problem Statement: Heap Validation, Indexing & Max-Heap Constructiontheorem

Consider the unsorted 0-indexed array A=[12,25,10,40,35,50,15]A = [12, 25, 10, 40, 35, 50, 15] (n=7n = 7):

  1. Which element index is the last internal node where Floyd's buildMaxHeap begins siftDown?
  2. Trace Floyd's buildMaxHeap(A) step by step to produce the final Max-Heap array.
  3. After calling extractMax() twice on your built Max-Heap, what sits at index 0 and what are the remaining heap leaf values?

Step-by-Step Solution:​

  1. Last Internal Node Index: ⌊n/2βŒ‹βˆ’1=⌊7/2βŒ‹βˆ’1=3βˆ’1=2\lfloor n / 2 \rfloor - 1 = \lfloor 7 / 2 \rfloor - 1 = 3 - 1 = \mathbf{2} (Nodes at indices 3, 4, 5, 6 are already trivial 1-node leaf heaps.)

  2. Floyd's Bottom-Up Trace (i = 2 down to 0):

    • i = 2 (10): Children [5]=50, [6]=15. Larger child is 50. Swap 10 <-> 50 β€…β€ŠβŸΉβ€…β€Š[12,25,50,40,35,10,15]\implies [12, 25, 50, 40, 35, 10, 15].
    • i = 1 (25): Children [3]=40, [4]=35. Larger child is 40. Swap 25 <-> 40 β€…β€ŠβŸΉβ€…β€Š[12,40,50,25,35,10,15]\implies [12, 40, 50, 25, 35, 10, 15].
    • i = 0 (12): Children [1]=40, [2]=50. Larger child is 50 ([2]). Swap 12 <-> 50, then sift 12 down against children [5]=10, [6]=15 β€…β€ŠβŸΉβ€…β€Š\implies swap 12 <-> 15 ([6]).
    • Built Max-Heap Array: [50, 40, 15, 25, 35, 10, 12].
  3. Two extractMax() Operations:

    • 1st Pop (50): Move 12 to root β€…β€ŠβŸΉβ€…β€Š[12,40,15,25,35,10]\implies [12, 40, 15, 25, 35, 10]. Sift 12 down (12 <-> 40, then 12 <-> 35) β€…β€ŠβŸΉβ€…β€Š[40,35,15,25,12,10]\implies [40, 35, 15, 25, 12, 10].
    • 2nd Pop (40): Move 10 to root β€…β€ŠβŸΉβ€…β€Š[10,35,15,25,12]\implies [10, 35, 15, 25, 12]. Sift 10 down (10 <-> 35, then 10 <-> 25) β€…β€ŠβŸΉβ€…β€Š[35,25,15,10,12]\implies \mathbf{[35, 25, 15, 10, 12]}.
    • New Root: 35 ([0]). Remaining leaves (⌊5/2βŒ‹=2…4\lfloor 5/2 \rfloor = 2 \dots 4): [15, 10, 12].

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  1. Can a heap simultaneously store identical elements (duplicates)?
    • Yes! Heap order enforces β‰₯\ge (or ≀\le), not strict inequality, so duplicate priorities work effortlessly.
  2. How many elements in an array of size nn are leaves of a Complete Binary Tree?
    • ⌈n/2βŒ‰\lceil n / 2 \rceil leaves sitting at indices ⌊n/2βŒ‹β€¦nβˆ’1\lfloor n/2 \rfloor \dots n - 1, leaving exactly ⌊n/2βŒ‹\lfloor n / 2 \rfloor internal nodes!
  3. In a Min-Heap of nn distinct integers, which indices can potentially hold the maximum key?
    • Any of the ⌈n/2βŒ‰\lceil n/2 \rceil leaf positions (floor(n/2) .. n-1) β€” finding it takes Θ(n)\Theta(n) comparisons.
Common Interview Traps: Architectural Trade-Offs
  • Claiming buildHeap Takes O(nlog⁑n)\mathcal{O}(n \log n) Time: Top-down construction (n pushes) IS O(nlog⁑n)\mathcal{O}(n \log n), whereas Floyd's bottom-up siftDown visits half the array at height 0 (cost 0), a quarter at height 1, shrinking geometrically to strictly Θ(n)\Theta(n)!
  • Assuming Arbitrary Search / Delete in a Heap Is O(log⁑n)\mathcal{O}(\log n): Without maintaining an external hash-map tracking every key's live array index, locating an arbitrary element inside a heap costs O(n)\mathcal{O}(n) linear search! Only Root extract/peek have fast O(log⁑n)\mathcal{O}(\log n) / O(1)\mathcal{O}(1) 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.

πŸš€ Level Up Your Engineering Mindset

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
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.