
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

CS483 Fall03 - Sample Homework 1, Solutions, Jana Koˇseck´a
Pseuso-code of the algorithm : Selection Sort(A,n) for i=1 to n-1 do % find the smallest element in A[i] ... A[n] min = A[i] ; loc = i ; for j = i+1 to n do if A[j] < min then min = A[j]; loc = j; endif end swap A[i] and A[loc] end
Analysis: We have two loops one for 1... n − 1 and one for i... n, and suppose that number of operations with a loop will take constant time c 1 and c 2. Then total time in the worst case will be
T (n) =
n∑− 1
i=
(c 1 +
∑^ n
j=i+
c 2 ) =
n∑− 1
i=
(c 1 + c 2 (n − i))
= c 1 (n − 1) + c 2
∑^ n
i=
i = c 1 (n − 1) + c 2 n(n − 1)/ 2 => T (n) = Θ(n^2 )
n , 1. Answer (using either limit or definition) : 1 = O(lg^2 n), lg^2 n^ =^ O(n^3 ), n^3 =^ O((^32 )n),^32 )n^ =^ O(2^2
n ).
a. T (n) = 4T (n/2) + n^2 Using Master’s theorem: a = 4, b = 2, f (n) = n^2 , log 2 4 = 2 Case 2 applies: f (n) = Θ(n^2 ) => T (n) = Θ(n^2 lg n). b. T (n) = T (n − 1) + n for n ≥ 2 and T (1) = 1 T (n) = T (n − 2) + n − 1 + n =... = 1 + 2 + 3 +... + (n − 1) + n == n(n − 1)/2 => T (n) = Θ(n^2 ) c. T (n) = 1 for n = 1 and T (n) = 3T ( n 2 ) +^ nlogn^ for^ n >^1 Master’s theorem: a = 3, b = 2f (n) = n lg n, lg 2 3 = 1.^585 ... >^ 1. Then^ f^ (n) =^ O(nlg^2 3 −) for some > 0 (e.g. using limits). Case 1 applies T (n) = Θ(nlg^2 3 ). d. T (n) = 6T ( n 5 ) + nlg^6 n a = 6, b = 5; f (n) = nlg^6 n, log 5 6 = 1. 11 ... Case 1 applies: f (n) = O(n^1.^1 −) => T (n) = Θ(nlog^5 6 ).
T (n) = T (n/3) + T (2n/3) + cn Lower bound is provided by the length of the shortest path in the recurrence tree. In this case the shortest branch has length lg 3 n and since at each level the cost is cn then T (n) = Ω(n lg 3 n) = Ω(n lg n).