for(int i=1; i*i <= n; i = i+1) {
for(int j = n; j >= 1; j/4) {
for(int k = 1; k <= j; k=k+1) {
f();
}
}
}
Why is the asymptotic complexity of this function O(n^{3/2})? I think, it should be O(sqrt(n)log(n)n). Is this the same to O(sqrt(n)n)? Then, it would be O(n^{3/2})..
- Outer loop is
O(sqrt(n)). - first inner loop is
O(log(n)). - second inner loop is
O(n).
The outer two loops (over
iandj) have bounds that depend onn, but the inner loop (overk) is bounded byj, notn.Note that the inner loop iterates
jtimes; assumingf()isO(1), the cost of the inner loop isO(j).Although the middle loop (over
j) iteratesO(log n)times, the actual value ofjis a geometric series starting withn. Because this geometric series (n + n/4 + n/16 + ...) sums to4/3*n, the cost of the middle loop isO(n).Since the outer loop iterates
sqrt(n)times, this makes the total costO(n^(3/2))