You are on page 1of 4

Selected Solutions for Chapter 6:

Heapsort
Solution to Exercise 6.1-1
Since a heap is an almost-complete binary tree (complete at all levels except pos-
sibly the lowest), it has at most 2
hC1
1 elements (if it is complete) and at least
2
h
11 = 2
h
elements (if the lowest level has just 1 element and the other levels
are complete).
Solution to Exercise 6.1-2
Given an n-element heap of height h, we know from Exercise 6.1-1 that
2
h
_ n _ 2
hC1
1 < 2
hC1
:
Thus, h _ lg n < h 1. Since h is an integer, h = ]lg n (by denition of ] ).
Solution to Exercise 6.2-6
If you put a value at the root that is less than every value in the left and right
subtrees, then MAX-HEAPIFY will be called recursively until a leaf is reached. To
make the recursive calls traverse the longest path to a leaf, choose values that make
MAX-HEAPIFY always recurse on the left child. It follows the left branch when
the left child is greater than or equal to the right child, so putting 0 at the root
and 1 at all the other nodes, for example, will accomplish that. With such values,
MAX-HEAPIFY will be called h times (where h is the heap height, which is the
number of edges in the longest path from the root to a leaf), so its running time
will be .h/ (since each call does .1/ work), which is .lg n/. Since we have
a case in which MAX-HEAPIFYs running time is .lg n/, its worst-case running
time is .lg n/.
6-2 Selected Solutions for Chapter 6: Heapsort
Solution to Exercise 6.4-1
(b) (c)
(d) (e) (f)
(g) (h) (i)
2 4 5 7 8 13 17 20 25
20
4
2 5
7 8 13 17
25
2
4 5
7 8 13 17
25 20
5
4 2
17 13 8 7
20 25
7
4 5
17 13 8 2
20 25
13
5 8
2 7 4 17
25 20
8
7 5
17 13 4 2
20 25
17
13 5
2 4 7 8
25 20
20
13 17
2 4 7 8
25 5
A
i
i
i i i
i
i i
(a)
25
13 20
2 17 7 8
4 5
Selected Solutions for Chapter 6: Heapsort 6-3
Solution to Exercise 6.5-2
2 2
2 2
8 1 8 1
8
1 10
i
8
1 -
15
13 9
5 12 8 7
4 0 6
(a)
15
13 9
5 12 8 7
4 0 6
(b)
15
13 9
0
12 10 7
4
5
6
(c)
i
15
5
10
0
12 9 7
4
13
6
(d)
i
Solution to Problem 6-1
a. The procedures BUILD-MAX-HEAP and BUILD-MAX-HEAP
0
do not always
create the same heap when run on the same input array. Consider the following
counterexample.
Input array A:
1 2 3 A
BUILD-MAX-HEAP.A/:
1
3 2
3
1 2
3 2 1 A
BUILD-MAX-HEAP
0
.A/:
1
-
2
- 1
3
2 1
3 1 2 A
b. An upper bound of O.nlg n/ time follows immediately from there being n 1
calls to MAX-HEAP-INSERT, each taking O.lg n/ time. For a lower bound
6-4 Selected Solutions for Chapter 6: Heapsort
of .nlg n/, consider the case in which the input array is given in strictly in-
creasing order. Each call to MAX-HEAP-INSERT causes HEAP-INCREASE-
KEY to go all the way up to the root. Since the depth of node i is ]lg i , the
total time is
n
X
iD1
.]lg i / _
n
X
iDdn=2e
.]lg {n=2/
_
n
X
iDdn=2e
.]lg.n=2//
=
n
X
iDdn=2e
.]lg n 1/
_ n=2 .lg n/
= .nlg n/ :
In the worst case, therefore, BUILD-MAX-HEAP
0
requires .nlg n/ time to
build an n-element heap.

You might also like