If we look at the outermost 2 loops we observe that there are 1 + 2 + 3 ... + n - 1
iterations. Using standard facts about series summation (or induction if you want an in depth proof), we can see that this O(n^2)
.
The innermost loop is log(n)
. The easiest way to prove this is with the master theorem. You can write a recurrence in the form:
LoopIterations(n) = LoopIterations(n/2) + 1
Where LoopIterations
is the number of iterations from a starting point n. The master theorem tells us that LoopIterations(n)
is O(log(n))
.
One subtlety is that our initial condition for the recurrence is LoopIterations(n^2)
, but since log(n^2) = 2 log(n)
this doesn't affect the final computational complexity, since we can ignore constant factors.
@Kaushal Covered why you can multiply the above two results to get O(n^2 log(n))
, though I would add that if you want to convince yourself of that you can do induction for these kind of problems though that can get quite long.