Definition. Amortised complexity and array doubling
[comp1110-43]
Definition. Amortised complexity and array doubling
[comp1110-43]When an array-backed collection is full, we cannot simply extend it, because arrays have a fixed length. Instead, we create a new array of double the current size and copy all elements across. This makes any individual add that triggers a resize cost \(\mathrm {O}(n)\). However, such expensive calls are rare: after doubling, the next \(\frac {n}{2}\) insertions are cheap (\(\mathrm {O}(1)\) each).
Amortised analysis spreads the cost of an expensive operation across the many cheap operations that preceded it. If we charge each element a small constant at the time it is first inserted to "pre-pay" for its eventual copy, we find that each insertion costs \(\mathrm {O}(1)\) on average over any sequence of \(n\) insertions, even though individual insertions may cost \(\mathrm {O}(n)\).
To see that this is the case here, consider the overall cost of what we have done so far after \(n + 1\) insertions. In the worst case, we just had to double the size of the array for the last insertion, meaning that the array now has size \(2n\). That last doubling involved \(n\) copies. The doubling before that involved \(\frac {n}{2}\) copies. The one before that involved \(\frac {n}{4}\) copies. And so on. All of those copy operations sum up to less than \(2n\) copies. This means that per insertion (of the \(n + 1\) insertions we did so far), we made less than 2 copies (a constant), plus the constant amount of work for the insertion. The combination of those costs is still constant.