Complexity of algorithm (asymptotic) -
can confirm me complexity of algorithm o(n^2)?
a = 0 b = 0 c = n while (b <= c) { (j = b; j<=c; j++) { = j * j -2 * j + 3 } b = b + 3 c = c + 2 }
the inner loop executes c - b + 1 times. each execution of inner loop body a = j * j -2 * j + 3 takes constant (bounded) time (assuming we're dealing fixed-width integer types, otherwise depend on multiplication algorithm used [and addition, that's hard implement in way multiplication faster]), execution of body of outer loop o(d) (Θ(d) even), d = c - b + 1.
the updates of variables controlling outer loop
b = b + 3 c = c + 2 decrease difference c - b 1 in each execution of outer loop's body, hence outer loop executed n+1 times, , have total of o(n²), since
n n+1 ∑ (n+2k - (3k) +1) = ∑ j = (n+1)(n+2)/2 k=0 j=1 it Θ(n²), unless compiler optimises , sets variables final values directly.
answer original question typo:
the inner loop
for (j = b; j==c; j++) will execute either once - when b == c or not @ all, body of outer loop o(1). updates in outer loop
b = b + 3 c = c + 2 mean difference c-b decreases 1 each time loop body executed, so
b = 0 c = n while (b <= c) will execute n+1 times - total: o(n).
Comments
Post a Comment