Professional Documents
Culture Documents
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
T n
T n=
T n
T n
T n=
<
T n=
>
T n
T n
T n
T n
T n=
n=
T n
n=
T n=
n=
n=
n=
T n=
:::
n=
n=
:::
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
) + (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 dened 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
r =
A p::r
r =
O n
T n
T n
n