Max Heap
- Tags
- comp-sci
A heap with the max-heap property:
For every node \( n \) (other than the root) the value of that node is no-greater than its parent. \[ \forall i \in N A[\text{Parent}(n)] \geq A[n] \]
From this it follows that the root-node of a max-heap is the largest element of the heap.
def max_heapify(arr, i):
l = left(i)
r = right(i)
# Pick the larger of the current node
# or left and right sub-node.
largest = i
if l <= len(arr) and arr[l] > a[i]:
largest = l
if r <= len(arr) and arr[r] > a[largest]:
largest = r
if largest != i:
swap(arr, i, largest)
max_heapify(arr, largest)
To [see page 12, build] a max-heap we apply alg:max_heapify to the tree bottom-up. Because max-heapify assumes the left and right sub-trees are valid heaps we can't do so top-down. This approach can be seen in alg:build_max_heap. We loop from \( \lfloor \frac{n}{2} \rfloor \) down because the values from \( \lfloor \frac{n}{2} \rfloor + 1, \ldots, n \) are all leaf nodes and leaves are already heaps (trivially).
def build_max_heap(arr):
for i in reversed(range(len(arr) // 2)):
max_heapify(arr, i)