COMP/MATH 3804 – Design and Analysis of Algorithms I
Assignment 2
Due June 3 at the beginning of class
Write down your name and student number on
every
page. The questions
must
be answered in order and
your assignment sheets
must
be stapled. Late assignments will not be accepted. Students are encouraged to
collaborate on assignments, but at the level of discussion only. When writing down the solutions, students
must do so in their own words.
1. Suppose we are given
n
integers
a
1
,a
2
,...,a
n
and an integer
i
with
1
≤
i
≤
n
. We want to report
the
i
smallest numbers (
i.e.
, the smallest, second smallest, third smallest,
...
,
i
-th smallest numbers)
in sorted order
.
(a) One possible strategy is to use SELECT to compute the smallest, second smallest, third smallest,
...
,
i
-th smallest individually. How long does this take?
Solution:
SELECT takes
O
(
n
)
time. Since we run it
i
times, the total running time is
O
(
ni
)
.
(b) One possible strategy is to sort the list and return the ﬁrst
i
elements. How long does this take?
Solution:
Sorting takes
O
(
n
log
n
)
time using,
e.g.
, merge sort. It then takes
O
(
i
)
time to report
the ﬁrst
i
elements, for a total of
O
(
n
log
n
+
i
) =
O
(
n
log
n
)
.
(c) One possible strategy is to put all the elements into a heap and call EXTRACT-MIN
i
times. How
long does this take?
Solution:
Building a heap on
n
elements takes
O
(
n
)
time. Each EXTRACT-MIN takes
O
(log
n
)
time, and we perform
i
of them. The total running time is thus
O
(
n
+
i
log
n
)
.
(d) Describe and analyze an algorithm to perform this operation in
O
(
n
+
i
log
i
)
time.
Solution:
We ﬁrst call SELECT to determine the
i
-th smallest element. We then call PARTITION
(the same one that is used as a subroutine of SELECT) in order to partition the input around the
i
-th smallest element. At this point, we have the smallest, second smallest, third smallest,
...
,
i
-th
smallest numbers, but they may not be in sorted order. To sort these
i
numbers takes
O
(
i
log
i
)
time using,
e.g.
, merge sort. The total time is therefore
O
(
n
+
i
log
i
)
.
2. Recall the UNION-FIND structure based on trees. Suppose we would also like to also support the