for (int i = 0; i < n; i++ ) {
for (int j = 0; j < n; j++ {
Simple Statement
}
}
for (int k = 0; i < n; k++ {
Simple Statement
Simple Statement
Simple Statement
Simple Statement
Simple Statement
}
Simple Statement*25
For the nested loop, I find a time complexity of 1 (for int i = 0) + n + 1 (for i < n) + n (for i++) * [ 1 (for int j = 0 ) + 1 + n ( for j < n) + n ( for j++) ] + n (for the simple statement). This is (1+n+1+n)(1+1+n+n)+n = (2 + 2n)(2+2n)+n = 4n^2 + 9n + 4.
For the following loop, I find a time complexity of 1 (for int k = 0) + n + 1 (for i < n) + n (for k++) + 5n (for the five simple statements). This is 1+n+1+n+5n = 7n+2. For the next 25 simple statements, I find they have a time complexity of 25.
So the total time complexity is 4n^2 + 8n + 4 + 5n + 2 + 25 = 4n^2 + 16n + 31, however, my book says the time complexity is n^2 + 5n + 25.
What have I done wrong?
Edit: It is now apparent that the book is telling the time complexity of only the simple statements. I suppose now my question is this (as it was in the title): What is the time complexity of the algorithm?
Your book is counting only the number of
SimpleStatements
executed.