

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Algorithm Analysis CS 2420 Page 1
For iterative algorithms, it is often easy to see the complexity – but recursive algorithms are a bit more difficult.
T ( n )= aT ( n / b )+Ο( nk ) - each call reduces the problem size by a factor of b and makes “a”
recursive calls. The last term indicates the amount of work per call. (as a function of a power of n). Note, in terms of complexity, we don’t care whether the work is done before or after (or in between) the recursive calls.
void doit(int n) { if (n==1) return; for (i=0; i<n; i++) x = x + i; doit(n/2); doit(n/2); }
void doit(int n) { if (n==1) return; for (i=0; i<n; i++) x = x + i; doit(n/2); }
void doit(int n) { if (n==1) return; x++; doit(n/2); doit(n/2); }
void doit(int n) { if (n==1) return; for (i=0;i<n; i++) x = x + i; doit(n-1); }
Algorithm Analysis CS 2420 Page 2
n T(n) 2 10 4 10 8 10 16 11 32 8
n T(n) 2 10 4 17 8 32 16 66 32 130
n T(n) 2 10 4 10 8 15 16 20 32 25
n T(n) 2 8 4 32 8 500 16 65, 32 4 x10^9
n T(n) 2 2 4 8 8 25 16 64 32 161
Another way to check if the complexity is correct is to divide the experimental time by the complexity. Below represents three attempts at finding the complexity. The first is an overestimate. Notice how the ratio goes to zero. The second is correct, showing the constant is approximately 4.3. The third is an underestimate. Notice how the ratio increases.
n Actual time n 3 ratio n 2 ratio n log n ratio 4 75 64 1.17 16 4.7 8 9. 8 219 512 0.43 64 3.4 24 9. 16 1104 4096 0.27 256 4.3 64 17. 32 4398 32768 0.13 1024 4.3 160 27. 64 17632 262144 0.07 4096 4.3 384 45.