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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -