Beruflich Dokumente
Kultur Dokumente
Heapsort
Since a heap is an almost-complete binary tree (complete at all levels except pos-
sibly the lowest), it has at most 2hC1 1 elements (if it is complete) and at least
2h 1 C 1 D 2h elements (if the lowest level has just 1 element and the other levels
are complete).
If you put a value at the root that is less than every value in the left and right
subtrees, then M AX -H EAPIFY 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
M AX -H EAPIFY 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,
M AX -H EAPIFY 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 M AX -H EAPIFY’s running time is ‚.lg n/, its worst-case running
time is .lg n/.
6-2 Selected Solutions for Chapter 6: Heapsort
25 20 17
13 20 13 17 13 5
8 7 17 2 8 7 4 2 8 7 4 2
i
5 4 5 25 i 20 25
(a) (b) (c)
13 8 7
8 5 7 5 4 5
2 7 4 i 17 2 4 13 i 17 2 i 8 13 17
20 25 20 25 20 25
(d) (e) (f)
5 4 2
4 2 2 5 i i 4 5
i 7 8 13 17 7 8 13 17 7 8 13 17
20 25 20 25 20 25
(g) (h) (i)
A 2 4 5 7 8 13 17 20 25
Selected Solutions for Chapter 6: Heapsort 6-3
15 15
13 9 13 9
5 12 8 7 5 12 8 7
i
4 0 6 2 1 -∞ 4 0 6 2 1 10
(a) (b)
15 15
i
13 9 13 10
i
5 12 10 7 5 12 9 7
4 0 6 2 1 8 4 0 6 2 1 8
(c) (d)
B UILD -M AX -H EAP.A/:
1 3 A 3 2 1
2 3 2 1
of .n lg n/, consider the case in which the input array is given in strictly in-
creasing order. Each call to M AX -H EAP -I NSERT causes H EAP -I NCREASE -
K EY to go all the way up to the root. Since the depth of node i is blg ic, the
total time is
Xn X n
‚.blg ic/ ‚.blg dn=2ec/
iD1 iDdn=2e
X
n
‚.blg.n=2/c/
iDdn=2e
X
n
D ‚.blg n 1c/
iDdn=2e
n=2 ‚.lg n/
D .n lg n/ :
In the worst case, therefore, B UILD -M AX -H EAP0 requires ‚.n lg n/ time to
build an n-element heap.