嵌套循环时间复杂度

时间:2015-09-07 21:02:15

标签: algorithm time-complexity

for ( i =  0;  i <= n; i = i +2 )
     for ( j = n; j >=  i;  j - - )

我知道外循环运行n / 2 + 1次

我无法弄清楚内循环会运行多少次

if we assume n = 10 

the inner loop runs for 10 times when i = 0 
the inner loop runs for 8 times when i = 2
and so on but i cant figure out what time complexity would that be? 

2 个答案:

答案 0 :(得分:0)

看起来内循环内的平均迭代次数为n/2。然后:

(n/2 +1) * n/2

答案 1 :(得分:0)

让我们假设一个任意n并考虑i0 <= i <= n。 你说的是外循环将运行n/2+1次。

让我们看看内部循环将为给定的ni运行多少次。内循环的j值从i到n如此

 i, i+1, i+2, i+3, ..., n   
 |______________________|
            |
        n-i+1 terms

所以基本上内循环所采用的步数是这个序列中的术语数,如果你看的是n-i+1(你的问题实际上有错误;如果是n = 10和{{ 1}},内循环需要11步而不是10步。

因此,要获得两个循环所做的步骤总数,我们需要i = 0。让sum n-i+1 for i=0 to i<=n, i+=2表示这个总和。然后:

S(n-i+1)

现在 S(n-i+1) = S(n+1) - S(i) = (n+1)*S(1) - S(i) # since n+1 is a constant we can pull it out = (n+1)*(n/2 + 1) - S(i) # S(1) is just equal to the number of steps of the outer loop which is n/2+1 = (n+1)*(n/2 + 1) - (0 + 2 + 4 + ... + n) arithmetic progression。这个总和是S(i) = 0 + 2 + 4 + ... + n因此我们的总和是

n*(n/4+1/2)

所以主导词是 = (n+1)*(n/2 + 1) - n*(n/4+1/2) = n^2/2 + n + n/2 + 1 - n^2/4 -n/2 = n^2/4 + n + 1 导致n^2的复杂性。