Complexity of Loops

The time complexity of a function is O(1) if does not contain a loop, recursive function, or any other non-constant time function. 

The time complexity of a loop is also O(1) if it has a constant no of iterations

Recursive function time complexity is also O(1) if it runs a constant no of times.

Linear Loops:

The time complexity of a loop is O(n) which is linear. If the loop variable is incremented or decremented by constant

Nested Loops: 

1. The time complexity of nested loops is equal to the number of times the innermost statement is executed. For example, the following sample loop has O(n2time complexity:

   for (int i = 1; i <=n; i += c) {

       for (int j = 1; j <=n; j += c) {

          // some O(1) expressions

       }

   }

 

2. When one of the loops is divided and multiplied by constant and other loop is incrementing or decrementing by constant. 

   for (int i = 1; i <=n; i += c) {

       for (int j = 1; j <=n; j /= c) {

          // some O(1) expressions

       }

   }

The time complexity of the above loop is The time complexity is O(nlogn).


Logarithmic Loops:

1. The Time Complexity of a loop is considered as O(log2n)  if the loop variable is divided/multiplied by a constant amount. Consider the following two for loops:


for (int i = 1; i <=n; i *= c) {
       // some O(1) expressions
   }
for (int i = n; i > 0; i /= c) {
       // some O(1) expressions
   }

The Time Complexity of above two loops will be logC(n).

2. Time Complexity of a loop is considered as O(loglogn) if the loop variable is reduced/increased exponentially by a constant

amount.

// Here c is a constant greater than 1   
   for (int i = 2; i <=n; i = pow(i, c)) { 
       // some O(1) expressions
   }




Comments

Popular posts from this blog

Worst, Average and Best Case Analysis of Algorithms

Asymptotic Analysis