Lecture 5
Lecture 5
Heap Sort
For max-heaps (largest element at root), max-heap property: for all nodes
i,
excluding the root, A[PARENT(i )] ≥ A[i ].
For min-heaps (smallest element at root), min-heap property: for all nodes
i,
excluding the root, A[PARENT(i )] ≤ A[i ].
BUILD-MAX-HEAP(A,n) 9
do MAX-HEAPIFY (A,i,n) 6 5
i
0 8 2 1
1 2 3 4 5 6 7 8
9 6 5 0 8 2 1 3
3
The height of a node is the number of edges from the node to the deepest
leaf.
The depth of a node is the no of edges from the root of the node.
H ea pify()
e by Max- es of
k don f no d
Wor nu m ber o
on the height h.
• Starting with the root (the maximum element), the algorithm places the maximum
element into the correct place in the array by swapping it with the element in the last
position in the array.
• “Discard” this last node (knowing that it is in its correct place) by decreasing the heap
size, and calling MAX-HEAPIFY on the new (possibly incorrectly-placed) root.
• Repeat this “discarding” process until only one node (the smallest element) remains,
and therefore is in the correct place in the array.
BUILD-MAX-HEAP: O(n)
• For loop: n − 1 times
• exchange elements: O(1)
• MAX-HEAPIFY: O(lg n)
Time: (1).
HEAP-INCREASE-KEY(A,i,key)
1. If key<A[i]
2. error” new key is smaller than the current key”.
3. A[i]= key
4. While i>1 and A[parent(i)]<A[i]
5. swap(A[parent(i)], A[i])
6. i=parent(i)
The running time of HEAP-INCREASE-KEY(A,i,key) is