Heap

Context: FIT1008_MOC ยท the efficient implementation of a Priority Queue (ADT) ยท backbone clustering its bottom-up construction ยท a complete binary tree under two invariants

Quick Revision

  • ๐ŸŽฏ Objective: complete + heap-ordered binary tree โž” add/get_max โ€” the array-backed priority queue.
  • ๐Ÿ“ฆ Core Components: complete โž” balanced, height | heap-order โž” parent โ‰ฅ child | addโ†’rise, get_maxโ†’sink | build bottom-up.
  • โšก Key Constraint: ops , peek , build (not ) โž” but only min/max, no arbitrary search.

๐Ÿ“ Core

1. The Heap (Two Invariants)

  • Complete โž” every level full except possibly the last, filled left-to-right โž” balanced.
  • Heap-order โž” every node its children โž” max at the root (min-heap is the dual).
  • Array representation โž” 1-indexed, no pointers: , โž” cache-friendly vs a pointer Binary Tree.

2. Operations (Rise / Sink)

  • add โž” append at then rise (swap up while > parent).
  • get_max โž” return index 1, move last leaf to root, shrink, then sink.
  • Sink rule โž” swap with the larger child (else a bigger sibling stays beneath); both ops are one root-to-leaf path โ‡’ .

3. Bottom-Up Construction ( Heapify)

  • Mechanism โž” sink each internal node right-to-left from to root (leaves are trivial heaps).
  • Cost โž” , not โ€” sum of node heights .
  • Boundary โž” requires all elements up front (offline); a stream must use add/rise ( each).

โš™๏ธ Core Implementation

๐Ÿ”น rise / sink

๐Ÿ”น Bottom-up build_heap

โš–๏ธ Core Decision Matrix

Operation / BuildComplexityTrigger / Note
add (rise)one root-to-leaf path
get_max (sink)one path
peekthe root
build (bottom-up) heights
build (ร— add)each insert rises to the root
Heapsortin-place, space, unstable

When It Flips: a heap is always balanced + constant-space-per-element but supports only min/max (search(x) is ) โž” use a balanced BST when you need search, ordered iteration, or predecessor/successor. Bottom-up build never dominates heapsort: .

๐Ÿ“Š Exam Execution Trace

Applied Exercise

Problem: Prove bottom-up heap construction is , not . Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: build is โ€” most nodes are near-leaves (sink ); the height is paid by very few.

๐Ÿง  Active Recall