There are several points to make here:
Having three nested loops doesn't imply O(n^3)
complexity. It depends on the loops and what happens within the loops. It could be anything between O(1) and never halting.
Your teacher should specify what should be measured more precisely: the number of steps for the entire piece of code? Or just the two inner loops, ignoring the outer loop?
You need to specify what the variable parameters are. In this case it's pretty clear what it is (probably n
, and not i
or j
), but it helps to be precise.
The code doesn't run because there is a syntax error: b[i] ) reader.nextInt();
. So strictly speaking, there is no time complexity to reason about here.
OK, now assuming that the line should actually read b[i] = reader.nextInt();
, the variable parameter is n
, and the whole code should be measured: your teacher is right that the entire code runs in O(n^2)
, because the outer and the second loops share the same index variable i
. So the outer loop iterates exactly once.
It doesn't really make sense to be much more precise than O(n^2)
unless you define precisely what counts as 1
. So stating something that looks precise like n^2 +4n
is pretty much meaningless without much more context.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…