algorithms hw2
algorithms hw2
algorithms hw2
2
Problem 1.e (10 points)
Please prove that your algorithm solves the problem (i.e., prove the
correctness) using your loop invariant and pseudocode.
Algorithm 1 MinList
Input: a two-dimensional array of integers M with n rows and m columns
Output: a list M ′ containing the minimum integer in each row
1: M ′ = []
2: for i = 1 to n do
3: min ← ∞
4: for j = 1 to m do
5: print(”Checking element j of row: ”)
6: for k = 1 to m do
7: print(M [i][k])
8: end for
9: print(“\n”)
10: if M [i][j] < min then
11: min ← M [i][j]
12: end if
13: end for
14: M′.append(min)
15: end for
16: return M′
3
2,4,6-time complexity = O(M^2) because line 6 takes O(m) for each iteration but is nested
in the j for loop which also takes O(M) time therefore the innermost loop runs in O(m^2).
The outermost loop runs only n times. The print statement inside the innermost loop runs in
O(1) but it runs O(m^2) times. Every other line either runs in O(n),O(m), or O(1) therefore
the time complexity for the entire algorithm is O(m^2)