Reputation: 1203
I know this is a general question but I really do need to clear my doubt as I am studying about time complexities. I did try to look it up before posting here but found mixed answers.
My question is, when inserting items in an unsorted array considering it is not full the complexity would be O(1) however if it is full it would be O(n) since we would need to copy all the items to a new array. So would we say that the best case complexity of insertion in an array is O(1) and worst case is O(n) or should we say both best and worst case are both O(n)?
Upvotes: 0
Views: 5193
Reputation: 14866
Indeed worst case insertion is O(n)
if you have to copy the whole array into a larger array. But you must remember, it is the amortize cost we care about.
Think about it this way: how often do I have to copy the whole array ? Once in n
times.
So for n-1
I will pay O(1)
and for the final insertion O(n)
.
In total ~2n
for n
insertions. Average O(1)
per op.
Maybe it is easier for you to think about it as O(2)
.
Now to maintain that, each time the array is filled, twice that size must allocated, so for each item you insert, you pay extra 1 for the time you might need to copy the corresponding item in the first half of the array.
Upvotes: 2