Amortized Analysis
The strategy for arbitrary inserting and removing sequence is incorrect. Consider the following scenario:
The current size of the array is
1) inserting
We assume that inserting and copying elements between arrays takes
We will choose
Now, when there is space in the array, insertion takes
e.g. when we start with an array of size
This is a geometric series, and the copy costs are
Thus, the copying of
amortized constant time per insertion.
2) removing
We assume that removing elements also takes
We can choose to halve the size of the array (which still has
Suppose we start with an array of size
Thus, we come to a total number of copy operations of
Equivalent to the argumentation for copying and inserting elements, copying and removing
inserting + removing
Since inserting and element takes
informal first draft:
a)
Since we also also did it like this in the exercise lesson, I've chosen to double the array each time it is resized. Therefore
costs:
- insertion:
- insertion with resizing (happens every
time): - resizing the array from
to takes time - inserting the new element takes
time - total:
- resizing the array from
Therefore, for inserting
b)
Shrinking
We could shrink a vector when more than half of it is empty.
costs:
- deletion:
- deletion with resizing (happens every
time): - resizing the array from
to takes time - deleting the element takes
time - total:
- resizing the array from
Therefore, for removing
And insertion and deletion together take