分析运行时间

时间:2012-11-29 07:37:50

标签: algorithm complexity-theory time-complexity asymptotic-complexity

def foo(x):
    if x > 5:
        return foo(x–1) – foo(x-1)
    else:
        return 77

def bar(a,b):
    if (b > 0):
        return bar( bar(a, b+1) , b-1 )
    else:
        return 0 

有人walk me through可以找到这些的运行时间吗?对于foo,我的猜测是由于2次递归调用它是O(n^2)。可能也是Θ(n^2)吗?

对于bar,我没有任何线索,因为它是无限递归。

2 个答案:

答案 0 :(得分:0)

显然foo(n)不在多项式时间内:

T(n) = 2T(n-1)  , if n > 5
     = Theta(1) , otherwise

因此

T(n) = Theta(2^n)
只要bar(a,b)

b > 0就永远不会结束

答案 1 :(得分:0)

对于功能

          _________  77  if(x<=5)
         /
        /
 foo(x)- 
        \
         \_________    foo(x-1) - foo(x-1)   if(x>5)


let f(x) be time function for foo(x)

f(x) =   f(x-1) - f(x-1) // 2 (2^1)calls of f(x-2) happened for 1 level depth
f(x) =   [f(x-2) - f(x-2)] - [ f(x-2) - f(x-2)] (expanding f(x-1)) // 4(2^2) calls of f(x-2) happened for 2nd level depth
f(x)={[ f(x-3) - f(x-3)]-[ f(x-3) - f(x-3)]} - {[ f(x-3) - f(x-3)]-[ f(x-3) - f(x-3)]} // 8(2^3) calls  of  f(x-2) happened for 3rd level depth

让我打电话来完成程序......

but program terminates when x<=5,
 so program terminates in call f(x-i) when x-i<=5
that means i>=x-5 , 
at level i there are 2power(i) calls 
 ==> 2^i calls of f(x-i).
 since f(<=5)=1(1 is unit of measure) for i>=x-5 

所以f(n)= 2 ^(x-5)*(1)=&gt; O(2 ^ x)其中x是输入大小。如果我们用n复制x替换为O(2 ^ n)。

第二个问题

          _________  0  if(b<=0)
         /
        /
 bar(a,b)
        \
         \_________  foo( bar(a,b+1) ,b-1 )  if(b>0)

令t(n)为bar(a,b)的时间函数,其中n与b成比例,因为b是终止的决定因素。

扩大复发

t(a,b) = t( t(a,b+1), b-1) .
first  t(a,b+1) is executed it inturn calls t(a,b+2) and so on.... 
it will be infinite recursion .....   for b > 0  . 

据我所知,由于我们没有无限的限制(既没有下限也没有上限,所以没有θ表示法,也没有大符号表示omega表示法)我们也无法测量复杂度函数。(请更正我,如果我错了)

但是如果b <0那么它将在O(1)时间内完成......