Array
Overview
An Array is a non-primitive data type that stores a fixed-size, ordered collection of elements of the same type. Elements are stored in contiguous memory locations, allowing fast access using an index.
Arrays are the foundation upon which many other data structures are built.
Key Characteristics
- Fixed size (defined at creation)
- Homogeneous elements
- Index-based access
- Contiguous memory layout
Indexes usually start from 0.
How It Works
When an array is created:
- A continuous block of memory is allocated
- Each element occupies equal-sized space
- The index maps directly to a memory offset
Access formula:
address = base + (index × element_size)
Common Operations
| Operation | Time Complexity |
|---|---|
| Access | O(1) |
| Update | O(1) |
| Search | O(n) |
| Insert | O(n) |
| Delete | O(n) |
Example
Pseudocode
arr = [10, 20, 30, 40]
print(arr[2]) // 30
arr[1] = 25
Real-world Analogy
An array is like numbered lockers in a row. You can jump straight to locker 7, but adding a new locker in the middle causes rearrangement 🔢🧳.
Use Cases
- Storing lists of values
- Lookup tables
- Buffers
- Matrices and grids
- Building blocks for higher structures
Advantages
- Fast random access
- Simple structure
- Cache-friendly memory layout
Limitations
- Fixed size
- Costly insertions and deletions
- Requires contiguous memory
Variants
- Static array
- Dynamic array
- Multidimensional array