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?
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,
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..
then, taking n^2 common, we get
solve this series to get the answer
The statement total++; shall run following number of times:
The number of terms in the above expression = log(N^2) = 2log(N).
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.