Analyzing worst case order-of-growth

2019-07-22 19:38发布

I'm trying to analyze the worst case order of growth as a function of N for this algorithm:

for (int i = N*N; i > 1; i = i/2)
     for (int j = 0; j < i; j++) {
           total++;
     }

What I'm trying is to analyze how many times the line total++ will run by looking at the inner and outer loops. The inner loop should run (N^2)/2 times. The outer loop I don't know. Could anyone point me in the right direction?

4条回答
做个烂人
2楼-- · 2019-07-22 20:08

The outer loop runs exactly 2LOG (base 2) N + 1 times (Float to int conversion and remove decimal places). If you see the value decreases like N^2,N^2/2 , N^2/4 ... 1. ..

So the total number of times total ++ runs is,

Summazion( x from 0 to int(2LOG (base 2) N + 1)) N^2/2^x

查看更多
唯我独甜
3楼-- · 2019-07-22 20:18

for this question as the inner loop is depending upon the value of the variable that is changing by the outer loop (so u cant solve this simply by multiplying the values of inner and the outer loops). u will have to start writing the values in a and then try to figure out the series and then solve the series to get the answer..

like in your question, total++ will run..

n^2 + n^2/2 + n^2/2^2 + n^2/2^3 + .....

then, taking n^2 common, we get

n^2 [ 1 + 1/2 + 1/2^2 + 1/2^3 + ...]

solve this series to get the answer

查看更多
地球回转人心会变
4楼-- · 2019-07-22 20:20

The statement total++; shall run following number of times:

= N^2 + N^2 / 2 + N^2 / 4 ... N^2 / 2^k
= N^2 * ( 1 + 1/2 + 1/4 + ... 1/2^k )

The number of terms in the above expression = log(N^2) = 2log(N).

Hence sum of series = N^2 * (1 - 1/2^(2logN)) / (1/2)
                    = N^2 * (1 - 1/4N) / (1/2).

Hence according to me the order of complexity = O(N^2)
查看更多
淡お忘
5楼-- · 2019-07-22 20:23

The outer loop would run with a complexity of log(N) as the series reduces to half on every iteration . For example a binary search.

查看更多
登录 后发表回答