2. Heap is a “complete” binary tree, usually
represented as an array.
Types:
Min Heap (largest element at root)
A[parent(i)]≥A[i]
Max Heap
A[parent(i)]≤A[i]
3. “The root is the
maximum element of the
heap!”
Example of Max
Heapify
20. BUILD‐MAX‐HEAP(A)
1. heap‐size[A] ← length[A]
2. for i ← ⌊length[A]/2⌋ downto 1
3. do MAX‐HEAPIFY(A,i)
21. Heap sort has time complexity O(n log n). The reason is that the
height of a complete binary tree is log(n).
To fully heapify an element whose sub trees are already max-heaps,
we need to keep comparing the element with its left and right
children and pushing it downwards until it reaches a point where
both its children are smaller than it.
In worst case, we need to move an element from root to leaf node
making a multiple of log(n) comparisons and swaps. During the
build max heap stage, we do that for n/2 elements so the worst case
complexity of build heap step is n/2*log(n)~n log n.