Overview
Array is a data structure that lets you store multiple values in one variable. Each value in the array is called an element, and elements are accessed using their index, which starts at0 for the first element.
| Operations | Complexity | Description |
|---|---|---|
| Access/Edit i-th element | O(1) | Arrays give direct access to elements through their index. |
| Insert/Remove | O(n) | Adding or removing an element at a specific index requires shifting all later elements to make room or fill the gap. |
| Insert/Remove at end | O(1) | Adding or removing an element at the end only needs updating the last index. |
Background
Arrays are usually stored as contiguous memory blocks. This means all elements sit next to each other in memory with no gaps in between.Memory Layout Example
Memory Layout Example
When an array is created, the system allocates a block of memory large enough to hold all elements. The memory address of each element is based on the starting address of the array. The first element sits at the starting address, and each following element is placed at the next available address.If each integer takes 4 bytes, the memory addresses look like this:Because the memory is contiguous, accessing elements is efficient. The address of any element can be calculated from the starting address and the size of each element. This makes direct access possible without looping or searching.
- They have a fixed size declared ahead of time.
- They use a set amount of memory for the entire program.
- Trying to add more elements than the set size can lead to overflow or memory issues.
- They do not need a fixed size in advance.
- They can grow or shrink during runtime.
- Some languages give them a default starting capacity. When this capacity is exceeded, the array is resized.
- Resizing usually means creating a new larger block of memory, often 2x or 1.5x bigger, copying all existing elements into it, and freeing the old block.