Build-heap from the last parent
Updated
For i from Math.floor(n/2)-1 down to 0, heapify(i). Leaves are skipped. Index 0 is heapified last so the whole array is a heap.
What to focus on
Start at the last parent, never at n-1. n=3 starts at 0. n=4 starts at 1 then 0. n=1 starts at -1 and does nothing.
Worked examples
n=3
a = [9, 4, 1]- last parent 0
- heapify 0 → swap 9 with 1
Result: [1, 4, 9]
n=4
a = [9, 4, 1, 7]- last parent 1
- heapify 1: 4<=7
- heapify 0: 9 vs 4 and 1 → [1, 4, 9, 7]
Result: [1, 4, 9, 7]
n=1
a = [7]- last parent -1
- loop does not run
Result: [7]
Try it
Write buildHeap(a). a is the input array. Loop i from Math.floor(n/2)-1 down to 0. heapify uses left 2*i+1 and right 2*i+2. Return the min-heap. Print a after the loop. Start at the last parent, never at n-1. [9, 4, 1] → [1, 4, 9] [9, 4, 1, 7] → [1, 4, 9, 7] [7] stays
a is a non-empty array of 1–6 integers. Start at the last parent, never at n-1. lastParent = Math.floor(n/2)-1.