Nested Loop Time complexity

谁说胖子不能爱 提交于 2019-12-25 06:46:31

问题


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

I know the outer loop runs for n/2 + 1 times

i cant figure out how many times would the inner loop runs

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? 

回答1:


Looks like average number of iterations within inner loop is n/2. Then:

(n/2 +1) * n/2



回答2:


Let us assume an arbitrary n and consider an i such that 0 <= i <= n. You're right in saying that the outer loop will run for n/2+1 times.

Let's see how many times the inner loop will run for a given n and i. The inner loop's j values go from i to n like this

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

So basically the number of steps the inner loops takes is the number of terms in this sequence which if you look is n-i+1 (you actually have an error in your question; if n = 10 and i = 0, the inner loop takes 11 steps not 10).

So to get the total number of steps the two loops make, we need to sum n-i+1 for i=0 to i<=n, i+=2. Let S(n-i+1) denote this sum. Then:

 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)

Now S(i) = 0 + 2 + 4 + ... + n which is an arithmetic progression. The sum of this is n*(n/4+1/2) thus our total sum is

 = (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

And so the dominant term is the n^2 resulting in a complexity of O(n^2).



来源:https://stackoverflow.com/questions/32446002/nested-loop-time-complexity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!