You can simply understand outer-loop(with i
) because it loops exactly n
times. (1, 2, 3, ..., n). But inner-loop(j
) is little difficult to understand.
Let's assume that n
is 8. How much it loops? Starting with j = 1
, it will be increased as exponentially : 1, 2, 4, 8. When j
is over 8, loop will be terminated. It loops exactly 4 times. Then we can think general-form of this problem...
Think of that sequence 1, 2, 4, 8, .... If n
is 2^k (k is non-negative integer), inner-loop will take k+1
times. (Because 2^(loop-1) = 2^k) Due to the assumption : n = 2^k
, we can say that k = lg(n)
. So we can say inner-loop takes lg(n)+1
times.
When n
is not exactly fit to 2^k, it takes one more time. ([lg(n)]+1
) It's not a big deal with complexity though it has floor function. You can ingonre it this time.
So the total costs will be like this : n*(lg(n)+1)
. If you are familiar with Big-O notation, it can be expressed as : O(n lg n)
.