Exercise VII
Consider the following implementation of countup
:
public static void countup(int n) {
for (int i = 1; i <= n; i++) {
System.out.println(i);
}
}
public static void countup(int n) {
if (n > 1) {
countup(n - 1);
}
System.out.println(n);
}
Exercise Complete the following table. Use big Oh notation to asymptotically describe time/space complexities.
countup | Time Complexity | Space Complexity | Input Space | Auxiliary Space |
---|---|---|---|---|
First program | ||||
Second prog. |
Solution
countup | Time Complexity | Space Complexity | Input Space | Auxiliary Space |
---|---|---|---|---|
First | $O(n)$ | $O(1)$ | $O(1)$ | $O(1)$ |
Second | $O(n)$ | $O(n)$ | $O(1)$ | $O(n)$ |
Each recursive call creates a function activation record (or stack frame) in memory. Each activation record is a memory allocation for the function with space for local variables, etc. Each activation record for the recursive countup
requires $O(1)$ space and there will be $n$ of them, thus $O(n)$ total space.
Resources
- Activation Record entry on C2 Wiki.
- Wikipedia's entry on Call stack.