Time complexity of nested for-loop

前端 未结 6 698
花落未央
花落未央 2020-11-22 08:51

I need to calculate the time complexity of the following code:

for (i = 1; i <= n; i++)
{
  for(j = 1; j <= i; j++)
  {
   // Some code
  }
}
         


        
6条回答
  •  耶瑟儿~
    2020-11-22 09:27

    On the 1st iteration of the outer loop (i = 1), the inner loop will iterate 1 times On the 2nd iteration of the outer loop (i = 2), the inner loop will iterate 2 time On the 3rd iteration of the outer loop (i = 3), the inner loop will iterate 3 times
    .
    .
    On the FINAL iteration of the outer loop (i = n), the inner loop will iterate n times

    So, the total number of times the statements in the inner loop will be executed will be equal to the sum of the integers from 1 to n, which is:

    ((n)*n) / 2 = (n^2)/2 = O(n^2) times 
    

提交回复
热议问题