Cost of Resizing
- Determine the cost of dynamically resizing an array-based implementation of a stack.
Here is the implementation of push
.
@Override
public void push(T value) {
data[numElements++] = value;
if (numElements == capacity) {
grow();
}
}
We know grow()
is .
Exercise What is the running time of push
?
Solution
The worst-case asymptotic running time of push
is also .
Consider the data
array is constructed initially with the capacity of . We then perform "push" operation one after another.
Exercise What is the worst-case running time of push
per operation (rather than per algorithm).
Hint
We know the grow
operation will only be called for the push. Therefore,
- the first time we call
push
, its cost is really , - the second time we call
push
its cost is - the time we call
push
Solution
The cost of push
is for the first pushes. Then, for the push, we must grow the array, and so it will cost . After that, the push is again .