GrowableArray

ClassS04CS141 | recent changes | Preferences

Growable array

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+… + 2k = O(2k). (See GeometricSums .)

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


References


ClassS04CS141 | recent changes | Preferences
This page is read-only | View other revisions
Last edited May 4, 2004 7:14 pm by Neal (diff)
Search: