Solutions Test Chap1
Solutions Test Chap1
(Chapter 1)
Multichoice-Questions
1.
D. an (a is an integer > 3)
2.
B. C(n) = O(n3)
3. (1.5 pts) Given the recursive program with the following recurrence relation.
CN = 2CN-1 + 1 for N ≥2
C1 = 1
What is the complexity of the above program?
B. 2N - 1
4.
C. 19/6
Other questions
5. (1.25 pts) Given the algorithm that checks if a matrix a of order n is symmetric or not as
follows.
function symmetric(a, n)
// a is matrix n n
begin
for i := 1 to n-1 do
for j:= i + 1 to n do
if a[i, j] <> a[j, i] then return false;
return true
end
Analyze the complexity of this algorithm in the worst case, if comparison is the basic operation. .
Ans:
The worst case occurs when the matrix is symmetric or only a[n-1, n] <> a[n, n-1].
i=1 j runs from 2 to n n-1 comparisons
i=2 j runs from 3 to n n-2 comparisons
.
i = n-1 j runs from n-1 đến n 1 comparison
1
So, the total number of comparisons is:
1 + 2 + 3 + … + (n-2) + (n-1) = n(n-1)/2
The complexity of the algorithm in the worst-case is O(n2).
6. (1.25 pts) Given the recursive program with the following recurrence relation.
CN = CN-1 + 1 for N > 1
C1 = 0
Apply substitution method to find the complexity of the above algorithm.
Ans:
CN = CN-1 + 1
= CN-2 + 1 + 1 // substitute CN-1 with CN-2 + 1
= CN-3 + 1 + 1 + 1 = CN-3 + 3
.
.
CN = CN-(N-1) + (N-1) = C1 + (N-1) = N-1 O(N)
7. (1.5 pts) Given the recursive algorithm with the following recurrence relation.
CN = CN/2 + 1 N2
C1 = 1
a. Apply substitution method to find the complexity of the above algorithm. (1 pt)
b. What is the above algorithm? (0.5 pts)
Ans:
a) Assume N = 2n
C(2n) = C(2n-1) + 1
= C(2n-2 )+ 1 + 1 // substitute C(2n-1) with C(2n-2 )+ 1
= C(2n-3 )+ 1 + 1+ 1 = C(2n-3 )+ 3
.
..
= C(20 ) + n
= C1 + n = 1 +n
CN = n +1 = lgN +1 (since n = lgN)
CN lgN
b) The above algorithm is binary search.
2
8. (0.75 pts) Given the following algorithm, if multiplication is chosen as abstract operation,
describe its recurrence relation in terms of computational time.
Algorithm Q(n)
//Input: A positive integer n
if n = 1 return 1
else return Q(n-1) + 2*n – 1
Ans:
C(n) = C(n-1) + 1 for n > 1
C(1) = 0
9. (0.75 pts) When analyzing the complexity of an algorithm in average case, what is
characterizing the input data?
Ans:
When analyzing the complexity of an algorithm in average case, characterizing the input data
consists of two steps:
1. Determine the sampling space which represents the possible cases of input data (of size
n). Assume that the sampling space is S = { I1, I2,…, Ik}
2. Determine a probability distribution p in S which represents the likelihood that each case
of the input data may occur.
Ans:
Procedure NAIVE STRING MATCHING has two nested loops:
- outer loop repeats n – m + 1 times.
- inner loop repeats at most m times.
Therefore, the complexity of the algorithm in the worst-case is: O((n – m + 1)m), where n the
length of the text and m is the length of the pattern.
This algorithm belongs to brute-force strategy.