Array
Definition
Sequentially stored data in a continuous chunk of memory. Two types:
- Linear: fixed size
- Dynamic: reserves space for additional elements, when full allocates new chunk with double size and copies the previous values.
Pros and Cons
Pros: Fast access to elements.
Cons: Slow insertion.
Complexity
| Operation | Complexity - Linear | Complexity - Dynamic |
|---|---|---|
| Access | ||
| Search | ||
| Append | N/A | but amortized cost |
| Insertion | N/A | |
| Delete |
- Access: access through
start + (cellsize * index)(cellsize being different for each type). - Search: iterates through array and checks if the current value is the searched one.
- Append: if full, copies every value in new memory chunk, however thanks to the additional space in most cases the new chunk is not required.
- Insertion: if full, copies every value in new memory chunk, then shifts array and adds element.
- Deletion: removes value and shifts array.
Proof for amortized cost
In the case we add m elements to dynamic array
cost of doubling (nb copies):
total number of operations:
So appending m elements is , hence appending 1 element is on average.