Heaps
- A heap is a complete binary tree
- Every level must be filled out except the bottom level
- Min heaps every parent is smaller than its children
- This is known as a heap-order property
- The root contains the smallest value
- Keys are stored as the nodes
- Perfect for priority queues -> most efficient sort method

Insertion and Upheap
Adding a key has three steps:
- Insert at the next available lead
- Store the key there
- Upheap bubble the key up until heap-order is restored

Upheap terminates when k ≥ parent(k) or k reaches the root
- At most swaps →
Removal and Downheap
remove_min() always removes the root, to avoid breaking tree:
- Copy the last node’s key to the root
- Remove the last node
- Downheap sink the new root key down until heap-order is restored

Array-Based Heap
- Can represent a heap with
nkeys withnsize arrayaddcorresponds to inserting at rankn + 1remove_mincorresponds to removing at rankn
Node at index i | Left child | Right child | Parent |
|---|---|---|---|
| Formula | 2i + 1 | 2i + 2 | (i-1) // 2 |
| This is what makes heap-sort in-place possible |
- No extra memory needed for pointers or references
Heap Sort
With a heap-based priority queue, sorting n elements takes:
n×addcalls →n×remove_mincalls →- Total:
Merging Two Heaps
- We are given two heaps and a key
k - Create new heap with
kas root and two heaps as subtrees - Perform downheap to restore heap-order property

Bottom-up Heap Construction
- If you insert
nelements one by one -> to build heap - Bottom-up construction builds heap in time
- Merges pairs of small heaps across phases
In phase , heap pairs with keys merge into heaps with keys
-
Pair nodes and assign parent

-
Use downheap to restore heap-order

-
Repeat steps 1&2 until root node reached
Bottom-up vs One-by-One
Inserting
nelements one-by-one → to build
Bottom-up construction → to build
Either way, heap-sort itself is total