Find the time complexity, in worst case, in function of n = 2N , N >=0.
Find the recurrence relation and solve it.
public static void xpto(v, n){
if (n <= 1)
return;
n=n/2;
for(i=0;i<n;i=i+1)
v[i] = v[2i] + v[2i +1];
xpto(v, n);
}
T(1) = 1
recurrence equation by substituiton:
T(n) = 1 + 1 + (n + 1) + n + T(n/2)
T(n) = 3 + 2n + T(n/2)
T(n/2) = 3(2) + 2n(2) + T(n/4)
T(n/4) = 3(3) + 2n(3) + T(n/8)
T(n/8) = 3(4) + 2n(4) + T(n/16)
pattern found
T(n/8) = 3(4) + 2n(4) + T(n/2^4)
general recurrence in terms of k:
T(n) = 3(k) + 2n(k) + T(n/2^k)
if T(1) = 1 and T(n/2^k) we need to change 2^k by n, this means:
2^k = n
T(n) = 3(log n) + 2n(log n) + 1
The recurrence relation is solved.
Time complexity, in worst case is O(log(n))
Questions:
I am not sure how you got the constants, but let's assume for simplicity, that the operation v[i] = v[2i] + v[2i +1];
is of cost 1, and everything else is free. (It can be adjusted easily without harming the concept of the following calculations).
Based on that,
T(n) = n/2 + T(n/2)
Based on that, we can use master theorem case 1 with c=1, a=1,b=2
, and conclude T(n)
is in Theta(n^1)=Theta(n)
Firstly, if you got: T(n) = 3(log n) + 2n(log n) + 1
as your final solution, then the worst case complexity would not be log n
but rather n(log n)
because of the term 2n(log n)
.
From your initial recurrence relation: T(n) = 3 + 2n + T(n/2)
i did the following:
Assume n = 2^k and g(k) = T(n) such that:
g(k) = g(k-1) + 2*2^k + 3 (from simply substituting n=2^k and change of function)
g(k) = sum(i=1 to k) of (2*2^i + 3)
g(k) = 2 * (sum(i=1 to k) of (2^i)) + 3k
Using geometric progression, common ratio = 2:
g(k) = 2 * (2(1-2^k) / (1-2)) + 3k
g(k) = -4 + 4*2^k + 3k
Since we initially assumed n = 2^k, this means k = log n:
T(n) = -4 + 4n + 3(log n)
Hence the worst case complexity is O(n)
For the second part of your question:
n = 2N where N >= 0 simply means n is a set of even numbers since any positive integer multiplied by 2 will be even.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.