Design & Analysis of Algorithm (CSC-321) : Computer Sciences Department Bahria University (Karachi Campus)
Design & Analysis of Algorithm (CSC-321) : Computer Sciences Department Bahria University (Karachi Campus)
Lecture 6
Computer Sciences Department
Bahria University (Karachi Campus)
HeapSort
Heap
• Min heap
• Max heap
Max heap
Building a Heap
• Convert an array A[1 … n] into a max-heap (n = length[A])
• The elements in the subarray A[(n/2+1) .. n] are leaves
• Apply MAX-HEAPIFY on elements between 1 and n/2
Alg: BUILD-MAX-HEAP(A) 1
1. n = length[A] 4
2 3
2. for i ← n/2 downto 1 1 3
4 5 6 7
3. do MAX-HEAPIFY(A, i, n) 8
2 9 10
16 9 10
14 8 7
A: 4 1 3 2 16 9 10 14 8 7
5
Running Time of BUILD MAX HEAP
Alg: BUILD-MAX-HEAP(A)
1. n = length[A]
2. for i ← n/2 downto 1
O(n)
3. do MAX-HEAPIFY(A, i, n) O(lgn)
7
Running Time of BUILD MAX HEAP
• HEAPIFY takes O(h) the cost of HEAPIFY on a node i is
proportional to the height of the node i in the tree
h
T (n) ni hi 2i h i O(n)
h
h1 = 2 i=1 21
h2 = 1 i=2 22
h3 = 0 i = 3 (lgn) 23
• Idea:
– Build a max-heap from the array
– Swap the root (the maximum element) with the last
element in the array
– “Discard” this last node by decreasing the heap size
– Call MAX-HEAPIFY on the new root
– Repeat this process until only one node remains
10
Example: A=[7, 4, 3, 1, 2]
MAX-HEAPIFY(A, 1, 1)
11
Alg: HEAPSORT(A)
1. BUILD-MAX-HEAP(A) O(n)
2. for i ← length[A] downto 2
3. do exchange A[1] ↔ A[i] n-1 times
4. MAX-HEAPIFY(A, 1, i - 1) O(lgn)