TCP2101 Algorithm Design and Analysis La
TCP2101 Algorithm Design and Analysis La
Learning Outcomes
• Understand how heap and priority queue work.
1. (20 min) A heap is a complete binary tree in which the value of each node is greater than or equal to
the values of its children (parent >= children). Which of the following binary trees is not a heap?
Explain your answer.
1. 2. 3.
1 3 3
/ \ /
2 2 2
N. Parent < Child. N. Not complete. Y
4. 5. 6.
5 5 5
/\ /\ /
3 4 3 4 3
\ / / \
1 2 2 1
N. Not complete. Y N. Not complete.
2. (25 min) The following numbers are enqueued sequentially into a priority queue. Draw the resulting
heap for every enqueue.
42586937
1. 2. 3. 4.
4 => 4 4 4 4 5 5 8
/ => / / \ => / \ /\ / \
2 2 2 5 2 4 2 4 => 5 4
/ /
8 2
5. 6. 7. 8.
8 8 8 9 9 9 9 9
/\ /\ / \ / \ / \ / \ / \ / \
5 4 => 6 4 6 4 => 6 8 6 8 => 6 8 6 8 => 7 8
/\ /\ /\ / /\ / /\ /\ /\ /\ /\ /\ /\ /\
2 6 2 5 2 5 9 2 5 4 2 5 4 3 2 5 4 3 2 5 4 3 6 5 4 3
/ /
7 2
1
3. (25 min) In the previous question, the heap is formed by enqueuing a number at a time. It works but
it takes O(n lg n) time for n input because each enqueue takes O(lg n) time. A faster way to make a
heap out of an initial array in Ѳ(n) time without enqueuing one at a time (see Lecture 3 topic
Forming an Initial Heap). Draw the heap based on this idea. Your answer in this question might be
different from the previous one.
1. Initial 2. 3. 4. 5.
4 4 4 4 9
/ \ / \ / \ / \ / \
2 5 2 5 2 9 8 9 8 5
/\ /\ /\ /\ /\ /\ /\ /\ /\ /\
8 6 9 3 8 6 9 3 8 6 5 3 7 6 5 3 7 6 4 3
/ / / / /
7 7 7 2 2
4. (25 min) From the final heap you drew in the previous question, dequeue all numbers until the
priority queue is empty. Draw the resulting heap for every dequeue.
1. 2. 3. 4.
2 8 3 7 2 6 2 5
/ \ / \ / \ / \ / \ / \ /\ / \
7 8 => 7 4 7 4 => 6 4 6 4 => 5 4 5 4 => 3 4
/\ /\ /\ /\ /\ / /\ / /\ /\ / /
6 5 4 3 6 5 2 3 6 5 2 3 5 2 3 5 3 2 3 2
5. 6. 7. 8.
2 4 2 3
/ \ => / \ / => / 2 => 2 Empty
3 4 3 2 3 2
5. (5 min) Notice that you actually dequeue 9 first, then 8, 7, 6, 5, 4, 3, and 2 at last. The result is in a
form of sorting order. This sorting technique is known as Heapsort which will be discussed further in
Lecture 5.
6. (5 min) What is the time complexity for enqueue an element, dequeue an element, and forming an
initial heap? O(lg n), O(lg n), O(n).