Understand heap order
Updated
Min-heap order: for every i > 0, a[parent(i)] <= a[i], with parent(i) = Math.floor((i-1)/2). Check the parent, not left versus right.
What to focus on
Heap order is local parent-child. [1, 4, 9] is ordered. A BST would also want left < root; 4 left of 1 is fine in a heap.
Worked examples
holds
a = [1, 4, 9]- parent of 1 is 0: 1 <= 4
- parent of 2 is 0: 1 <= 9
Result: min-heap
deeper child
a = [1, 4, 9, 7]- parent of 3 is 1: 4 <= 7
- root 1 still <= 4 and 9
Result: min-heap
one node
a = [7]- no i > 0
- no parent to check
Result: min-heap
Try it
Write isHeap(a). a is the heap array. parent(i) = Math.floor((i-1)/2). Left child is 2*i+1. Right child is 2*i+2. Return true if a[parent(i)] <= a[i] for every i from 1 to n-1, else false. Print the parent checks. [1, 4, 9] → true [1, 4, 9, 7] → true [7] → true
a is a non-empty array of 1–6 integers. Check min-heap order parent <= children. parent(i) = Math.floor((i-1)/2).