Amortized Analysis

Feedback

The strategy for arbitrary inserting and removing sequence is incorrect. Consider the following scenario:
The current size of the array is 2n and it contains n elements. Now, I remove the last element. According to your algorithm, the array shrinks and costs O(n) time. Now the array is of length n and has n1 elements. Then I insert two elements to the end. You have to double the length of the array again, costing another O(n) time. Then I keep removing two elements, inserting two elements, ... Your strategy takes time O(n) every two operations.

1) inserting

We assume that inserting and copying elements between arrays takes O(1) time.

We will choose n=2k, doubling the array size every time the array is full.

Now, when there is space in the array, insertion takes O(1) time. When the array is full, however, it grows from 2i to 2i+1 elements and requires copying 2i elements.

e.g. when we start with an array of size 1, the array doubles

1,2,4,8,,2k1

This is a geometric series, and the copy costs are

i=0k12i=1(2k1)21=2k1=def. nn1

Thus, the copying of n elements takes O(n) time and the insertion of n elements takes amortized O(n) time, which translates to

O(n)n=O(1)

amortized constant time per insertion.


2) removing

We assume that removing elements also takes O(1) time.

We can choose to halve the size of the array (which still has n=2k length) every time the number of elements frops below 12 of the array's size.

Suppose we start with an array of size 2i, and the number of elements falls from 2i to 2i1. In this case, we shrink the array and copy 2i1 elements to the new array.

Thus, we come to a total number of copy operations of

i=0k12i==n1

Equivalent to the argumentation for copying and inserting elements, copying and removing n elements also takes amortized O(n) time, i.e. constant time per element.

inserting + removing
Since inserting and element takes O(1) and deleting also takes O(1), inserting + removing also takes amortized O(1+1)=O(1) constant time.


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

k=2n

costs:

Therefore, for inserting n elements:

O(n1inserting every time+1nnresizing every 1/n time)=O(n+1)=O(n)

b)
Shrinking
We could shrink a vector when more than half of it is empty.

costs:

Therefore, for removing n elements:

O(n1removing every time+1nnresizing every 1/n time)=O(n+1)=O(n)

And insertion and deletion together take

O(n)insertion+O(n)deletion=O(2n)=O(n)