Resources
Takeaways:
- Dynamic Arrays resize when they reach capacity, usually by doubling.
- Dynamic Arrays, for insertions, have a worse case Big O of
O(n)
(linear). But due to doubling, the amortized* time complexity of Dynamic Arrays isO(1)
(constant). - A Dynamic Array's space complexity is at worst
O(2n)
(immediately after doubling), withO(n)
being wasted space (the empty half of the array). Note:O(2n)
in Big O is reduced toO(n)
- therefore the space complexity of a Dynamic Array isO(n)
.
*Another way of saying average. Per Wikipedia:
amortized analysis considers both the costly and less costly operations together over the whole series of operations of the algorithm
Often, a data structure has one particularly costly operation, but it doesn't get performed very often. That data structure shouldn't be labeled a costly structure just because that one operation, that is seldom performed, is costly.
So, amortized analysis is used to average out the costly operations in the worst case.
Here's the finished implementation with test code:
If you found any errors in this post, please let me know!
Top comments (2)
Good tutorial JB. Looking forward to follow your posts. One point I would like to add though.
The operation Prepend can be done by calling AddAt(element, 0) method inside the Prepend method :)
Good catch, you are probably right!