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
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.
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
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).
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):
NB: the formula simplifications might contain errors. If you detect anything, please let me know.
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)