Solucio Parcial 2018 2019 Q2.eng
Solucio Parcial 2018 2019 Q2.eng
Solucio Parcial 2018 2019 Q2.eng
(1) f = O( g) : if α > 1.
(2) f = Ω( g) : if α ≤ 1.
(3) g = O( f ) : if α ≤ 1.
(4) g = Ω( f ) : if α > 1.
n √ n
(b) T (n) = Θ(2 2 ) = Θ( 2 )
(a) A call mystery(v, 0, v. size ()−1, m) permutes the elements of v so that (at least)
the m first positions of v contain the m smallest elements, sorted in increasing
order.
(b) When one makes a call mystery(v, 0, n−1, n), first int q = partition (v, l , r)
is executed with l = 0 and r = n−1, with cost Θ(n). Moreover, as the vector
contains different integers sorted in increasing order and the function partition
takes as a pivot the leftmost element, we have q = 0. Hence we have that the
call mystery(v, l , q, m) is made with q = l = 0 and so takes constant time.
Besides, p = 1. If n > 1 finally a recursive call mystery(v, q+1, r , m−p) is
made, where q+1 = 1, r = n−1 and m−p = n−1.
In turn, when executing this call the cost of int q = partition (v, l , r) is Θ(n −
1), again the cost of mystery(v, l , q, m) is Θ(1), and if n − 1 > 1 again a
recursive call mystery(v, q+1, r , m−p), is made, where q+1 = 2, r = n−1 and
m−p = n−2.
Repeating the argument, we see that the accumulated cost is
n
Θ ( n ) + Θ ( n − 1) + . . . + Θ ( 1) = Θ ( ∑ i ) = Θ ( n 2 ) .
i=1
1
Proposed solution to problem 3
2
We note that the result of calling search1 (x, A, 0, 0, N) is true if and only if x
occurs in A.
To analyse the cost of this call, first of all we study the general case of calling
search1 (x, A, i , j , n) as a function of n. Let T (n) be the cost in the worst case
of this call. As in the worst case 3 calls are made with last parameter n/2 and
the cost of the non-recursive work is constant, we have the recurrence:
(b) It is correct. Let us see that the loop maintains the following invariant: if x oc-
curs in A, then the occurrence is between rows 0 and i (included), and between
columns j and N − 1 (included). At the beginning of the loop, the invariant
holds. And at each iteration it is preserved:
• If A[i ][ j] > x then x cannot occur at row i: by the invariant we have that
if x occurs then it must be in a column from j to N − 1. But if j ≤ k < N
then A[i ][k] ≥ A[i ][ j] > x.
• If A[i ][ j] < x then x cannot occur at column j: by the invariant we have
that if x occurs then it must be in a row from 0 to i. But if 0 ≤ k ≤ i then
A[k][ j] ≤ A[i ][ j] < x.
Finally, if the program returns true with the return of inside the loop, the
answer is correct as A[i ][ j] = x. If it returns false with the return of outsi-
de the loop, then i < 0 or j ≥ N. In any case, by the invariant we deduce that x
does not appear in A.