You are on page 1of 6

Example 1

for (i =0, i< n, i++)


{
Block of Sts;
}

Example 2

for (i =n, i>0, i--)


{
Block of Sts;
}
Examples 3,4 Time complexity of nested loops is equal to the number of
times the innermost statement is executed.

for (int i = 1; i <=n; i += c) for (int i = n; i > 0; i -= c)


{ {
for (int j = 1; j <=n; j += c) for (int j = i+1; j <=n; j += c)
{ {
// statements; // statements;
} }
}
Example 5

for (i =0, i*i< n, i++) i*i < n


{ i2 > -n
Block of Sts; i2 = n
} i = n1/2

Example 6

for (i =0, i< n, i =i*2)


2 k >= n
{
2k=n
Block of Sts; K = log 2 n
}
Example 7

for (i =0, i< n, i++)


{
for (j =0, j< n, j*3)
  Block of Sts;
}

O(n log3 n)
Example 8

int count = 0; How many times count++ will run?


for (int i = n; i > 0; i /= 2) When i=n, it will run n times.
for (int j = 0; j < i; j++) When i=n/2, it will run n/2 times.
count++; When i=n/4, it will run n/4 times and so on.

Total number of times count++ will run is


 n+ n/2 +n/4 +...+1 = 2∗n.

You might also like