What is the complexity of this nested triple for loop?

后端 未结 5 1541
小蘑菇
小蘑菇 2020-12-14 22:55

I have searched a bit on StackOverflow and have understood the complexity up to the point of the j-loop, which is O(n2). However with the nested addi

相关标签:
5条回答
  • 2020-12-14 23:34

    This is quite tricky to explain without diagrams, but each nested loop will iterate "n" number of times before returning the iteration to the parent.

    So as jambono points out, each nested loop requires comparison/evaluation for each iteration of "n". So "n" is compared to the local variables in each loop (n*n*n) making O(n^3).

    Step the code in a debugger for a visual indication of how this complexity is processed by the machine.

    0 讨论(0)
  • 2020-12-14 23:46

    the k-loop has O(j-i) complexity

    the j-loop has O((n-i)*(n-i)) complexity

    the i-loop has O(n*n*n)=O(n^3) complexity

    anyway, you know that it is not O(n^2) because the first two loops are O(n^2) and it is not more than O(n^3) because there are only 3 loops

    0 讨论(0)
  • 2020-12-14 23:48

    Take a look at this example for evaluating worst case complexity.

    In essence, if you evaluate it line by line, you will get to something like O(n^3 / C), where C is some constant, normally skipped in such evaluations, leading to O(n^3).

    0 讨论(0)
  • 2020-12-14 23:59

    If you're accustomed to Sigma Notation, here is a formal way to deduce the time complexity of your algorithm (the plain nested loops, precisely):

    enter image description here

    NB: the formula simplifications might contain errors. If you detect anything, please let me know.

    0 讨论(0)
  • 2020-12-15 00:00

    First we'll consider loops where the number of iterations of the inner loop is independent of the value of the outer loop's index. For example:

    for (i = 0; i < N; i++) {
          for (j = 0; j < M; j++) {
                 sequence of statements
          }
      }
    

    The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times.
    Thus, the total complexity for the two loops is O(N2).
    Similarly the complexity for the three loops is O(N3)

    0 讨论(0)
提交回复
热议问题