\"Therefore, inserting N elements takes O(N) work total. Each insertion is O(1) on average, each though some insertions take O(N) time in the worst case.\" This quote is fou
Think to the cost of N insertions inside a resizable array as (I will use tilde notation here):
This is simply the cost of inserting a new element in the array multiplied for how many times you insert a new element, i.e., N:
Imagine you have a 64 cells array. Then, it means that the array has been resized for:
The 64 cell array has been resized 6 times, i.e., resize happens for log2(64) times. In general, now we know that for N insertion, we will perform log2(N) resize operations.
But what do we do inside each resize? We will copy the elements already present in the array in the new resized array: at resize "i", how many elements we wil copy? 2^i. With previous example:
So: