600.363/463 Solution to Homework 2
Due: Wednesday, 9/24
6.43
We want the output of heap sort to be in increasing order. Even if the input
array
A
is sorted in increasing order, each call to MAX
HEAPIFY(
A,
1) in the
procedure HEAPSORT(
A
) still takes
O
(log
n
) time.
So the running time of
heap sort is dominated by this and hence is
O
(
n
log
n
).
The cost of MAX
HEAPIFY does not change for the case where the input
is sorted in decreasing order and heap sort still runs in
O
(
n
log
n
) time.
62
Analysis of dary heaps
1. A
d
ary heap can be represented in a 1dimensional array as follows. The
root is keep in
A
[1], its
d
children are kept in order in
A
[2] through
A
[
d
+1],
their children are kept in order in
A
[
d
+ 2] through
A
[
d
2
+
d
+ 1], and so
on. The two procedures that map a node with index
i
to its parent and
to its
j
th child (for 1
≤
j
≤
d
), respectively, are:
DARYPARENT(
i
)
return
(
i

2)
/d
+ 1
DARYCHILD(
i, j
)
return
d
(
i

1) +
j
+ 1
(To convenience yourself that these procedures really work, verify that:
DARYPARENT(DARYCHILD(
i, j
))=
i
,
for any 1
≤
j
≤
d
. Notice that the binary eap procedures are a special
case of the above procedures when
d
=2.)
2. Since each node has
d
children, the height of a
d
ary heap with
n
nodes is
Θ(log
d
n
)=Θ(log
n
/lg
d
).
3. The procedure HEAPEXTRACTMAX given in the text for binary heaps
works fine for
d
ary heaps too. The change needed to support
d
ary heaps
is in HEAPIFY, which must compare the argument node to all
d
children
instead of just 2 children. The running time of HEAPEXTRACTMAX
is still the running time for HEAPIFY, but that now takes worstcase
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '09
 a
 Sort, running time, Binary heap

Click to edit the document details