The one problem we face with arrays is that its size is fixed. We can run out of space once the array has been filled up. This is pretty bad in production as we cannot really estimate the size of the array beforehand in many situations. Of course, we could allocate a huge array but we’d be wasting resources at the end of the day if they’re not populated. Sounds like a chicken and an egg problem.. How would we want to solve it?
The answer is dynamic array allocation. The concept is pretty simple. While instantiating a dynamic array, initially allocate a considerable size (for example, 10 as done in Java). Then once we run out of space we double its size from to . To delve a bit deeper into it, we first allocate an array of size , then copy the elements over to the newly allocated array. Then we give up the older array’s to the memory management system after making the array reference point to the new one. The figure below illustrates the state of the array before, during and after re-sizing the array.
|Figure: Dynamic Array Re-sizing (click image to enlarge)|
It can be noted that the same procedure holds good while we have too much space with us, once the array is only filled to , it gets re-sized to this number, instead of holding up space for all the elements.
Now let’s get into the interesting part, algorithmic complexity. For simplicity, let’s assume that the initial size of the array is .
The first question to be asked here is how many times do we have to double the array to reach a final capacity of . Before thinking in abstract terms, let us talk some numbers. Suppose if the capacity of my dynamic array is 16 right now, how many times have I doubled the capacity of my array? We’ve doubled 4 times (1 to 2, 2 to 4, 4 to 8, 8 to 16). Thus we can conlude that to reach the capacity of we must have doubled times.
The question to be asked next is how many times have we re-copied elements into a new array the original array is currently at capacity of and we’ve just re-sized to a capacity of ? Half of the elements of the original array has moved once, the quarter of the original array have moved twice, and so on. When we formulate this as a summation we get:
Notice that the we’re talking about the total number of movements (re-copies) of elements rather than how many times an element moves. This is useful because, when we look at insertions as a whole, we’ve just spent amount of work. This is really cool because, creating and managing a dynamic array framework is still guarenteed to be . Such a guarantee/cost analysis is formally known as an amortized guarantee/analysis depending on the context.