Native arrays in C++ require the size of the array to be declared in advance.

It is useful to define an Array class where the Array starts small and grows as needed (when cells out of range of the current table are accessed, the table is resized to accomodate the need for more cells). Resizing the array takes time proportional to the size of the new table (to allocate the new table, copy the old table into it, and initialize the newly allocated cells).

Because resizing is slow, it is good not to do it too often.
One good way to implement a growable array is to *double* the table size each time
the table needs to grow.

If we do this, then the total time spent supporting N array operations will be O(N+M), where M is the final size of the table (or, equivalently, the maximum index referenced in the table). In most applications, this is good enough because it is the time it would have taken simply to allocate the table of the desired size M in advance (assuming we knew M in advance, but with the growable array we don't have to).

Why is the total time O(N+M) to do N array operations (ending with a table of size M)?

To show this, use the fact that 1+2+4+… + 2^{k} = O(2^{k}). (See GeometricSums .)

Use the term 2^{i} in the sum to count the work done in growing the array
from size 2^{i-1} to size 2^{i}. Here 2^{k} is the final table size, which is M.

- Section 1.5.2 in GoodrichAndTomassia (thm 1.3.1, which gives a different analysis using
*amortization*). - ClassS04CS141/Hw1, problem 1 and solution in ClassS04CS141/Hwk1Soln