【问题标题】:Number execution of recursive function递归函数的执行次数
【发布时间】:2020-04-17 19:39:17
【问题描述】:

我有这个递归算法,T(n) 是执行 P(a, b) 的次数,n := b - a

int foo[] = ... // array of big enough size
function P(int a, int b) 
    if (a+1 < b) {
       int h = floor((a+b)/2)
       if foo[h] >= 0 then P(a, h)
       if foo[h] <= 0 then P(h, b)
    }
end function

如何计算 T(1)、T(2)、T(3) 和 T(4)

【问题讨论】:

  • hab 之间的中点。因此,[a, h][h, b] 的距离都具有ceil(n/2) 的长度(假设foo 是这样,您总是选择更大的范围)。有了这些知识,您应该能够计算出时间。
  • 你是怎么得出他们有长度 ceil(n/2) 的结论
  • 忽略四舍五入,我们可以计算h - a = (a + b) / 2 - a = b / 2 - a / 2 = (b - a) / 2 = n / 2b - h 的情况相同。

标签: algorithm recursion complexity-theory divide-and-conquer


【解决方案1】:

由于每次ab(作为函数的输入)之间的距离减半,时间复​​杂度为Theta(log(b-a))

【讨论】:

    猜你喜欢
    • 2021-02-18
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 2018-11-13
    • 2012-08-29
    • 2012-11-17
    相关资源
    最近更新 更多