MAT3500 - Algorithm Assignment - Part 2
Oct. 21st 2024
6
Min.
Assignment on Algorithm (Part 2)
Algorithm II - Hoang Anh Duc - MIM - HUS - VNU
Work 1.
Block
- Solution:
Block
Block
Block
Block
Work 2.
Block
- Solution:
Block
Block
Block
Work 5.
- Given algorithm:
1
2
3
4
5
6
7
8
# input: a: real number != 0, n: non-negative int
# output: a^n
procedure power(a, n):
if n = 0 then
return 1
else
return a * power(a, n - 1)
Markdown- (a) Prove the correctness of algorithm above.
-
(b) Construct a recurrence relation to evaluate the running time of algorithm above. Solve or estimate the recurrence relation you found.
- Solution:
Block
Block
Work 6.
- Given algorithm:
1
2
3
4
5
6
7
8
9
10
11
12
# input: a_1, a_2, ... , a_n: int sequence; i, j, x: int; 1 <= i <= j <= n
# output: if x in {a_i, a_{i+1}, ... , a_j} then return k in {i, i+1, ... , j}
# such that x = a_k; otherwise return 0
procedure linear_search(i, j, x):
if a_i = x then # correct position? return
return i
else
if i = j then # not found
return 0
else # found in rest of sequence
return linear_search(i + 1, j, x)
Markdown-
Construct a recurrence relation to evaluate the running time of algorithm above. Solve or estimate the recurrence relation you found.
-
Solution:
Block
Work 7.
- Given algorithm:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# input: a_1, a_2, ... , a_n: int sequence; i, j, x: int; 1 <= i <= j <= n
# output: if x in {a_i, a_{i+1}, ... , a_j} then return k in {i, i+1, ... , j}
# such that x = a_k; otherwise return 0
procedure binary_search(i, j, x):
m := floor((i + j) / 2)
if x = a_m then
return m
else
if x < a_m & i < m then
return binary_search(i, m - 1, x)
else
if x > a_m & j > m then
return binary_search(m + 1, j, x)
else
return 0
Markdown-
Construct a recurrence relation to evaluate the running time of algorithm above. Solve or estimate the recurrence relation you found.
-
Solution:
Block