Heap Sort
Heap Sort
(Heap Sort)
Lecture -14 - 17
Overview
BUILD-MAX-HEAP(A,n) 9
𝒇𝒐𝒓 𝒊 ← 𝒏/𝟐 𝒅𝒐𝒘𝒏𝒕𝒐 𝟏
do MAX-HEAPIFY (A,i,n) 6 5
0 8 2 1
1 2 3 4 5 6 7 8
9 6 5 0 8 2 1 3
3
Tighter analysis Proof
• For easy understanding, Let us take a complete binary
Tree,
𝑛 1Τ 𝑛
≤Ο 2
⟹ Ο(2 2 )
2 1−1Τ2 2
T(n) ⟹ Ο 𝑛
Hence the running time of BUILD-MAX-HEAP(A,n) is Ο 𝑛 in tight bound .
Tighter analysis Proof
∞
1
𝑥𝑘 = value of Infanite G P Series
1−𝑥
𝑘=0
∞
𝑥 𝑘 = (1 − 𝑥)−1
𝑘=0
Differentiate both side:
∞
1
𝑘. 𝑥 𝑘−1 = −1 1 − 𝑥 −2
−1 =
(1 − 𝑥)2
𝑘=0
Multiply x both side
∞
𝑥
𝑘. 𝑥 𝑘 ==
(1 − 𝑥)2
𝑘=0
The heapsort algorithm
Given an input array, the heapsort algorithm acts as
follows:
• Builds a max-heap from the array.
• 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.
Example
Analysis
• BUILD-MAX-HEAP: O(n)
• for loop: n − 1 times
• exchange elements: O(1)
• MAX-HEAPIFY: O(lg n)