[英]Given a recursive algorithm solve the recurrence relation and give the time complexity in worst case, this is correct?
Find the time complexity, in worst case, in function of n = 2N , N >=0. 在最坏的情况下,根据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: 以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)) 时间复杂度,在最坏的情况下是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];
我不确定您如何获得这些常数,但是为了简单起见,我们假设操作
v[i] = v[2i] + v[2i +1];
is of cost 1, and everything else is free. 的成本是1,其他一切都是免费的。 (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)
基于此,我们可以使用主定理案例1,其中
c=1, a=1,b=2
,并得出T(n)
在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)
. 首先,如果您得到:
T(n) = 3(log n) + 2n(log n) + 1
作为最终解决方案,那么由于该项,最坏情况下的复杂度不是log n
而是n(log n)
2n(log n)
。
From your initial recurrence relation: T(n) = 3 + 2n + T(n/2)
i did the following: 根据您的初始递归关系:
T(n) = 3 + 2n + T(n/2)
我执行了以下操作:
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. n = 2N,其中N> = 0只是意味着n是一组偶数,因为任何正整数乘以2都将是偶数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.