Uploaded by paparoupa5

cps130-duke-H5-solution

advertisement
CPS 130 Homework 5 - Solutions
1. Give asymptotic upper and lower bounds for the following recurrences. Assume ( ) is
constant for = 1. Make your bounds as tight as possible, and justify your answers.
(a) ( ) = 2 ( 4) + p
Solution: By the Master Theorem:
= 2, =p 4, = 1 2
= 2 = 4p= c
( ) = ( log4 )
(b) ( ) = 7 ( 2) + 3
Solution: By the Master Theorem:
= 7, = 2, = 3
=7 8= c
( ) = ( 3)
(c) ( ) = 7 ( 2) + 2
Solution: By the Master Theorem:
= 7, = 2, = 2
=7 4= c
( ) = ( lg 7)
(d) ( ) = 5 ( 5) + log
Solution: The Master Theorem does not apply. For simplicity we may assume
log = log5 and solve by iteration:
( ) = log5 + 5 ( 5)
= log5 + log5 ( 1) + 52 ( 52)
=
= log5 + log5 ( 1) + + log5(
) + 5k+1 ( 5k+1)
Note that 5k+1 = 1 when = log5 1. Then,
T n
n
T n
n
T n=
a
b
c
a
b
n
T n
T n
T n=
b
c
a
<
b
T n
n
n
a
T n
=
n
T n=
n
a
b
c
a
>
b
T n
n
T n
T n=
n
n
T n
n=
n
n=
n
T n=
n=
n
n=
n
n
n=
n
T n=
:::
n=
n=
:::
k
n=
n
k
n
() =
T n
=
logX
5n 1
k
=0
log
X5 n n
k
log5 (
n
n
+ (1)
=1 k
log
X5 n 1
=
+ (1)
k =1
= ( ln log5 )
n
k
n
n
k
) + (1)
T n=
:
2. (CLRS 7.1-2) What value of does Partition return when all elements in the array
[ ] have the same value? Modify Partition so that = ( + ) 2 when all elements
in the array [ ] have the same value.
Solution: The original partition element will return its index in the array which will be
. This element as de ned in Partition will be the last index of the array sent into the
function, i.e. = . To modify Partition, add a check for equality of at the beginning
of the code. If all of the values are equal, then return the middle index = ( + ) 2.
This will take ( ) time and will not increase the running time of the algorithm.
3. (CLRS 7.2-3) Show that the running time of Quicksort is ( 2) when the array
contains distinct elements and is sorted in decreasing order.
Solution: On the rst iteration of Partition the pivot element is chosen as the
rst
element of . Index is incremented once and is decremented until it reaches the pivot,
i.e. the entire length of . Partition returns to Quicksort the rst element of ,
which recursively sorts one subarray of size 1 and one of size
1. This process is
repeated for the subarray of size 1. The running time of the entire computation is
then given by the recurrence:
(
2
( ) = (1)
( 1) + ( ) otherwise
2
= ( )
q
A p::r
q
p
r =
A p::r
q
q
r
n
q
p
r =
O n
n
A
i
A
j
A
A
n
n
T n
n
T n
n
n
:
2
Download