algorithm - Algorithmic complexity of o(n) -
i started playing algorithms this princeton course , observed following pattern
o(n)
double max = a[0]; (int = 1; < n; i++) if (a[i] > max) max = a[i];
o(n^2)
for (int = 0; < n; i++) (int j = i+1; j < n; j++) if (a[i] + a[j] == 0) cnt++;
o(n^3)
for (int = 0; < n; i++) (int j = i+1; j < n; j++) (int k = j+1; k < n; k++) if (a[i] + a[j] + a[k] == 0) cnt++;
the common pattern here nesting in loop grows exponent increases. safe assume if have 20-for loops complexity 0(n^20)?
ps: note 20 random number picked, , yes if nest 20 loops in code there wrong you.
it depends on loops do. example, if change end of 2nd loop 3 iterations this:
for (int = 0; < n; i++) (int j = i; j < i+3; j++) if (a[i] + a[j] == 0) cnt++;
we o(n)
the key whether number of iterations in loop related n , increases linearly n does.
here example 2nd loop goes n ^ 2:
for (int = 0; < n; i++) (int j = i; j < n*n; j++) if (a[i] + a[j] == 0) cnt++;
this o(n^3)
Comments
Post a Comment