You need a little math to see this. The inner loop iterates Ξ(1 + log [N/(i+1)]) times ( 1 + is required, since for i >= N/2 , [N/(i+1)] = 1 and the logarithm is 0, but the cycle repeats once). j takes values (i+1)*2^k until it is at least N , and
(i+1)*2^k >= N <=> 2^k >= N/(i+1) <=> k >= log_2 (N/(i+1))
using mathematical division. Therefore, updating j *= 2 is called ceiling(log_2 (N/(i+1))) times, and the condition is checked 1 + ceiling(log_2 (N/(i+1))) times. So we can record the overall work
N-1 N β (1 + log (N/(i+1)) = N + N*log N - β log j i=0 j=1 = N + N*log N - log N!
Now Stirlingβs formula tells us
log N! = N*log N - N + O(log N)
therefore, we find that the overall work performed is indeed O(N) .
Daniel Fischer
source share