简体   繁体   English

计算复杂性和递归——这个分析正确吗?

[英]Computational complexity and recursion - Is this analysis correct?

在此处输入图像描述

Hi, I have a doubt about this resolution of this algorithm analysis, specifically referred to the return min(L[i:j+1]) : why is it considered O(n)?: it always refers to a defined slice, with a limited possible dimension (j<=i+2)嗨,我对此算法分析的分辨率有疑问,特别是指返回 min(L[i:j+1]) :为什么它被认为是 O(n)?:它总是指一个定义的切片,与有限的可能维度 (j<=i+2)

For simplicity, consider size of the list to be a power of 3.为简单起见,将列表的大小视为 3 的幂。


Algorithm算法

if j-i+1 <= 3:
    # Compute their minimum
    return min(i:j+1)

The if statement forms the base case. if语句 forms 是基本情况。 Time complexity of above statements is O(1) .上述语句的时间复杂度为O(1) However, the if statement will be executed n times.但是, if 语句将被执行n次。


Recursion Tree递归树

                                     T(n)
                                       |
                 ______________________|______________________
                |                      |                      |
                |                      |                      |
             T(n/3)                 T(n/3)                 T(n/3)
                |                      |                      |
         _______|_______        _______|_______        _______|_______
        |       |       |      |       |       |      |       |       |
        |       |       |      |       |       |      |       |       |
     T(n/9)  T(n/9)  T(n/9) T(n/9)  T(n/9)  T(n/9) T(n/9)  T(n/9)  T(n/9)

        .       .       .      .       .       .      .       .       .
        .       .       .      .       .       .      .       .       .
        .       .       .      .       .       .      .       .       . 
        .       .       .      .       .       .      .       .       .    
      T(1)    T(1)    T(1)   T(1)    T(1)    T(1)   T(1)    T(1)    T(1)    --- (n/3) * T(1)      

It should be obvious from the recursion tree, that for an array of size n , if statement will be executed n/3 times.从递归树中应该很明显,对于一个大小为n的数组, if语句将被执行n/3次。 Hence, overall complexity of if statement is O(n) .因此, if语句的整体复杂度为O(n)


The reason if is executed n/3 times and not n is that recursion ends when we encountered an sub-array of size 3 . if被执行n/3次而不是n的原因是当我们遇到大小为 3 的子数组时递归结束 If the the recursion came to an end when we encountered an sub-array of size 1, then it would have been executed for n times.如果递归在遇到大小为 1 的子数组时结束,那么它将执行 n 次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM