You are on page 1of 1

Christian L.

Lungsod BSCPE 2
Discrete Mathematics Cpe 4

Algorithm 1.

a. Show that this algorithm uses O(n3) comparisons to compute the matrix M.
Ans. The innermost assignment will take constant time to do the comparison and
assignment. The innermost loop (with k as the index) will run no more than n times. [The
minimum possible value to initialize k is i + 1, and the minimum possible value for i is 1
and the maximum value k will ever go to is j and the maximum value that j will go to is n.]
The middle loop (with j as the index) will run no more than n times. [The minimum
possible value to initialize j is i + 1 which is 2. The maximum value j will go to is n] The
outermost loop (with i as the index) will run n times. Therefore the runtime of the nested
loops will take O(n) · O(n) · O(n) time The initialization step of M will do one assignment
for every element in M. M has n 2 elements, so this step will take O(n 2) time. Therefore
the total runtime will be O(n3 + n2) = O(n3).
b. Show that this algorithm uses Ω(n³) comparisons to compute the matrix M. Using this
fact and part (a), conclude that the algorithms uses Θ(n³) comparisons. [Hint: Only
consider the cases where i≤n/4 and j≥ 3n/4 in the two outer loops in the algorithm.]

Ans. Let's consider the number of comparisons made in the innermost loop when i ≤
n/4 and j ≥ 3n/4. In this case, the length of the subsequence being considered is at least
n/2, so the number of comparisons made in the innermost loop is at least n/2.
Therefore, the total number of comparisons made in the innermost loop over all such
pairs (i,j) is at least (n/4) * (n/4) * (n/2) = (n³)/32.

On the other hand, we can upper bound the number of such pairs (i,j) as follows. The
number of values of i such that i ≤ n/4 is at most n/4, and the number of values of j such
that j ≥ 3n/4 is also at most n/4. Therefore, the number of pairs (i,j) such that i ≤ n/4 and
j ≥ 3n/4 is at most (n/4) * (n/4) = (n²)/16.

Therefore, the total number of comparisons made in the innermost loop over all such
pairs (i,j) is at most (n²)/16 times the number of comparisons made in the innermost
loop, which is O(n). Hence, the total number of comparisons made in the innermost loop
over all such pairs (i,j) is O((n³)/16).

Since the total number of comparisons made by the algorithm is O(n³), and the number
of comparisons made in the cases where i ≤ n/4 and j ≥ 3n/4 is at least (n³)/32 and at
most O((n³)/16), we can conclude that the number of comparisons made in the
remaining cases (i,j) is at most O((n³)/32).

Therefore, the total number of comparisons made by the algorithm is at most O((n³)/32)
+ O((n³)/16) + O((n³)/2) = O(n³), which is the same as the overall time complexity of the
algorithm.

You might also like