4.1 Arrays¶
An array is a linear data structure that stores elements of the same type in contiguous memory. An element's position in the array is its index. Figure 4-1 shows the main concepts and storage layout.

Figure 4-1 Array definition and storage layout
4.1.1 Common array operations¶
1. Initializing an array¶
We can initialize an array with or without explicit values. When values are not specified, most programming languages initialize the elements to \(0\):
/* Initialize arrays */
let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0]
let slice: &[i32] = &[0; 5];
// In Rust, [i32; 5] is an array with a specified length; &[i32] is a slice
// Rust array lengths are determined at compile time and must be constants
// Vector is Rust's usual dynamic array type
// To make extend() easier to implement, we treat a vector as an array below
let nums: Vec<i32> = vec![1, 3, 2, 5, 4];
Visualize execution
2. Accessing an element¶
Because array elements occupy contiguous memory, their addresses are easy to calculate. Given the array's address (the address of its first element) and an index, the formula in Figure 4-2 gives the element's address, allowing direct access.

Figure 4-2 Calculating an array element's memory address
The first element has index \(0\), which may seem unintuitive because counting from \(1\) feels more natural. However, an index essentially describes an offset from the starting memory address. The first element's offset is \(0\), so index \(0\) makes sense.
Array access is very efficient: any element can be accessed directly in \(O(1)\) time.
/* Access an element at a random index */
int randomAccess(int[] nums) {
// Choose a random number in the interval [0, nums.length)
int randomIndex = ThreadLocalRandom.current().nextInt(0, nums.length);
// Get and return the randomly selected element
int randomNum = nums[randomIndex];
return randomNum;
}
/* Access an element at a random index */
int RandomAccess(int[] nums) {
Random random = new();
// Randomly select a number from [0, nums.Length)
int randomIndex = random.Next(nums.Length);
// Get and return the randomly selected element
int randomNum = nums[randomIndex];
return randomNum;
}
/* Access an element at a random index */
function randomAccess(nums) {
// Choose a random index in the interval [0, nums.length)
const random_index = Math.floor(Math.random() * nums.length);
// Get and return the randomly selected element
const random_num = nums[random_index];
return random_num;
}
/* Access an element at a random index */
function randomAccess(nums: number[]): number {
// Choose a random index in the interval [0, nums.length)
const random_index = Math.floor(Math.random() * nums.length);
// Get and return the randomly selected element
const random_num = nums[random_index];
return random_num;
}
/* Access an element at a random index */
fun randomAccess(nums: IntArray): Int {
// Randomly select a number in [0, nums.size)
val randomIndex = ThreadLocalRandom.current().nextInt(0, nums.size)
// Get and return the randomly selected element
val randomNum = nums[randomIndex]
return randomNum
}
Visualize execution
3. Inserting an element¶
Array elements sit next to one another, with no room between them for more data. As shown in Figure 4-3, inserting into the middle requires shifting every element at or after the insertion point one position toward the end, then assigning the new element at the desired index.

Figure 4-3 Inserting an element into an array
Because an array's length is fixed, inserting an element causes the last element to be lost. We will discuss the solution in the section on lists.
def insert(nums: list[int], num: int, index: int):
"""Insert element num at index `index` in the array"""
# Shift all elements at and after index `index` one position to the right
for i in range(len(nums) - 1, index, -1):
nums[i] = nums[i - 1]
# Assign num to the element at index `index`
nums[index] = num
/* Insert element num at index `index` in the array */
void insert(int *nums, int size, int num, int index) {
// Shift all elements at and after index `index` one position to the right
for (int i = size - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// Assign num to the element at index `index`
nums[index] = num;
}
/* Insert element num at index `index` in the array */
void insert(int[] nums, int num, int index) {
// Shift all elements at and after index `index` one position to the right
for (int i = nums.length - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// Assign num to the element at index `index`
nums[index] = num;
}
/* Insert element num at index `index` in the array */
void Insert(int[] nums, int num, int index) {
// Shift all elements at and after index `index` one position to the right
for (int i = nums.Length - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// Assign num to the element at index `index`
nums[index] = num;
}
/* Insert element num at index `index` in the array */
func insert(nums []int, num int, index int) {
// Shift all elements at and after index `index` one position to the right
for i := len(nums) - 1; i > index; i-- {
nums[i] = nums[i-1]
}
// Assign num to the element at index `index`
nums[index] = num
}
/* Insert element num at index `index` in the array */
func insert(nums: inout [Int], num: Int, index: Int) {
// Shift all elements at and after index `index` one position to the right
for i in stride(from: nums.count - 1, to: index, by: -1) {
nums[i] = nums[i - 1]
}
// Assign num to the element at index `index`
nums[index] = num
}
/* Insert element num at index `index` in the array */
function insert(nums, num, index) {
// Shift all elements at and after index `index` one position to the right
for (let i = nums.length - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// Assign num to the element at index `index`
nums[index] = num;
}
/* Insert element num at index `index` in the array */
function insert(nums: number[], num: number, index: number): void {
// Shift all elements at and after index `index` one position to the right
for (let i = nums.length - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// Assign num to the element at index `index`
nums[index] = num;
}
/* Insert element _num at index in the array */
void insert(List<int> nums, int _num, int index) {
// Shift all elements at and after index `index` one position to the right
for (var i = nums.length - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// Assign _num to the element at index
nums[index] = _num;
}
/* Insert element num at index `index` in the array */
fn insert(nums: &mut [i32], num: i32, index: usize) {
// Shift all elements at and after index `index` one position to the right
for i in (index + 1..nums.len()).rev() {
nums[i] = nums[i - 1];
}
// Assign num to the element at index `index`
nums[index] = num;
}
/* Insert element num at index `index` in the array */
void insert(int *nums, int size, int num, int index) {
// Shift all elements at and after index `index` one position to the right
for (int i = size - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// Assign num to the element at index `index`
nums[index] = num;
}
/* Insert element num at index `index` in the array */
fun insert(nums: IntArray, num: Int, index: Int) {
// Shift all elements at and after index `index` one position to the right
for (i in nums.size - 1 downTo index + 1) {
nums[i] = nums[i - 1]
}
// Assign num to the element at index `index`
nums[index] = num
}
### Insert element num at index `index` in the array ###
def insert(nums, num, index)
# Shift all elements at and after index `index` one position to the right
for i in (nums.length - 1).downto(index + 1)
nums[i] = nums[i - 1]
end
# Assign num to the element at index `index`
nums[index] = num
end
Visualize execution
4. Removing an element¶
Similarly, as shown in Figure 4-4, removing the element at index \(i\) requires shifting every element after \(i\) one position toward the beginning.

Figure 4-4 Removing an element from an array
After removal, the old final entry is no longer meaningful, so we do not need to change it explicitly.
Visualize execution
Overall, inserting and removing array elements have these drawbacks.
- High time complexity: Both operations take \(O(n)\) time on average, where \(n\) is the array length.
- Lost elements: Since the length is fixed, insertion loses any element pushed beyond the array's bounds.
- Wasted memory: We can allocate a longer array and use only its beginning, so any final entries lost during insertion are unused. However, this leaves some memory wasted.
5. Traversing an array¶
Most programming languages let us traverse an array either by index or by visiting its elements directly:
def traverse(nums: list[int]):
"""Traverse the array"""
count = 0
# Traverse the array by index
for i in range(len(nums)):
count += nums[i]
# Iterate directly over the array elements
for num in nums:
count += num
# Iterate over both the indices and the elements
for i, num in enumerate(nums):
count += nums[i]
count += num
/* Traverse the array */
func traverse(nums []int) {
count := 0
// Traverse the array by index
for i := 0; i < len(nums); i++ {
count += nums[i]
}
count = 0
// Iterate directly over the array elements
for _, num := range nums {
count += num
}
// Iterate over both the indices and the elements
for i, num := range nums {
count += nums[i]
count += num
}
}
/* Traverse the array */
func traverse(nums: [Int]) {
var count = 0
// Traverse the array by index
for i in nums.indices {
count += nums[i]
}
// Iterate directly over the array elements
for num in nums {
count += num
}
// Iterate over both the indices and the elements
for (i, num) in nums.enumerated() {
count += nums[i]
count += num
}
}
/* Traverse the array elements */
void traverse(List<int> nums) {
int count = 0;
// Traverse the array by index
for (var i = 0; i < nums.length; i++) {
count += nums[i];
}
// Iterate directly over the array elements
for (int _num in nums) {
count += _num;
}
// Traverse the array using forEach
nums.forEach((_num) {
count += _num;
});
}
Visualize execution
6. Finding an element¶
To find a specified element, traverse the array and compare each value with the target. Return the index when a match is found.
Because an array is a linear data structure, this is called linear search.
Visualize execution
7. Expanding an array¶
In a complex system, a program cannot ensure that memory immediately after an array is available, so extending it in place is unsafe. Therefore, in most programming languages, an array's length is fixed.
To expand an array, create a larger one and copy every element into it. This takes \(O(n)\) time and can be expensive for a large array. The code is as follows:
def extend(nums: list[int], enlarge: int) -> list[int]:
"""Extend the array length"""
# Initialize an array with the extended length
res = [0] * (len(nums) + enlarge)
# Copy all elements from the original array to the new array
for i in range(len(nums)):
res[i] = nums[i]
# Return the new, extended array
return res
/* Extend the array length */
int *extend(int *nums, int size, int enlarge) {
// Initialize an array with the extended length
int *res = new int[size + enlarge];
// Copy all elements from the original array to the new array
for (int i = 0; i < size; i++) {
res[i] = nums[i];
}
// Free memory
delete[] nums;
// Return the new, extended array
return res;
}
/* Extend the array length */
int[] extend(int[] nums, int enlarge) {
// Initialize an array with the extended length
int[] res = new int[nums.length + enlarge];
// Copy all elements from the original array to the new array
for (int i = 0; i < nums.length; i++) {
res[i] = nums[i];
}
// Return the new, extended array
return res;
}
/* Extend the array length */
int[] Extend(int[] nums, int enlarge) {
// Initialize an array with the extended length
int[] res = new int[nums.Length + enlarge];
// Copy all elements from the original array to the new array
for (int i = 0; i < nums.Length; i++) {
res[i] = nums[i];
}
// Return the new, extended array
return res;
}
/* Extend the array length */
func extend(nums []int, enlarge int) []int {
// Initialize an array with the extended length
res := make([]int, len(nums)+enlarge)
// Copy all elements from the original array to the new array
for i, num := range nums {
res[i] = num
}
// Return the new, extended array
return res
}
/* Extend the array length */
func extend(nums: [Int], enlarge: Int) -> [Int] {
// Initialize an array with the extended length
var res = Array(repeating: 0, count: nums.count + enlarge)
// Copy all elements from the original array to the new array
for i in nums.indices {
res[i] = nums[i]
}
// Return the new, extended array
return res
}
/* Extend the array length */
// JavaScript Array is a dynamic array and can be extended directly
// For learning purposes, this function treats Array as a fixed-length array
function extend(nums, enlarge) {
// Initialize an array with the extended length
const res = new Array(nums.length + enlarge).fill(0);
// Copy all elements from the original array to the new array
for (let i = 0; i < nums.length; i++) {
res[i] = nums[i];
}
// Return the new, extended array
return res;
}
/* Extend the array length */
// Note: TypeScript Array is a dynamic array and can grow directly
// For learning purposes, this function treats Array as a fixed-length array
function extend(nums: number[], enlarge: number): number[] {
// Initialize an array with the extended length
const res = new Array(nums.length + enlarge).fill(0);
// Copy all elements from the original array to the new array
for (let i = 0; i < nums.length; i++) {
res[i] = nums[i];
}
// Return the new, extended array
return res;
}
/* Extend the array length */
List<int> extend(List<int> nums, int enlarge) {
// Initialize an array with the extended length
List<int> res = List.filled(nums.length + enlarge, 0);
// Copy all elements from the original array to the new array
for (var i = 0; i < nums.length; i++) {
res[i] = nums[i];
}
// Return the new, extended array
return res;
}
/* Extend the array length */
fn extend(nums: &[i32], enlarge: usize) -> Vec<i32> {
// Initialize an array with the extended length
let mut res: Vec<i32> = vec![0; nums.len() + enlarge];
// Copy all elements from the original array to the new one
res[0..nums.len()].copy_from_slice(nums);
// Return the new, extended array
res
}
/* Extend the array length */
int *extend(int *nums, int size, int enlarge) {
// Initialize an array with the extended length
int *res = (int *)malloc(sizeof(int) * (size + enlarge));
// Copy all elements from the original array to the new array
for (int i = 0; i < size; i++) {
res[i] = nums[i];
}
// Initialize the newly added space
for (int i = size; i < size + enlarge; i++) {
res[i] = 0;
}
// Return the new, extended array
return res;
}
/* Extend the array length */
fun extend(nums: IntArray, enlarge: Int): IntArray {
// Initialize an array with the extended length
val res = IntArray(nums.size + enlarge)
// Copy all elements from the original array to the new array
for (i in nums.indices) {
res[i] = nums[i]
}
// Return the new, extended array
return res
}
### Extend the array length ###
# Ruby Array is a dynamic array that can grow directly
# For learning purposes, this function treats Array as a fixed-length array
def extend(nums, enlarge)
# Initialize an array with the extended length
res = Array.new(nums.length + enlarge, 0)
# Copy all elements from the original array to the new array
for i in 0...nums.length
res[i] = nums[i]
end
# Return the new, extended array
res
end
Visualize execution
4.1.2 Strengths and limitations of arrays¶
An array stores elements of one type in contiguous memory. These known properties give the system opportunities to optimize operations.
- Space efficiency: Data occupies a contiguous block with no extra structural overhead.
- Random access: Any element can be accessed in \(O(1)\) time.
- Cache locality: Accessing an element loads not only that element but also nearby data into the cache, speeding up later operations.
Contiguous storage also has limitations.
- Slow insertion and deletion: With many elements, these operations require substantial shifting.
- Fixed length: Once initialized, an array cannot change length; expansion requires copying all data into a new array.
- Wasted space: Any allocated space beyond actual needs is unused.
4.1.3 Typical applications of arrays¶
Arrays are fundamental, widely used data structures. They appear throughout algorithms and underpin more complex structures.
- Random access: To draw random samples, store data in an array and generate random indices to select elements.
- Sorting and searching: Arrays are the most common structures for these algorithms. Quick sort, merge sort, and binary search operate primarily on arrays.
- Lookup tables: An array can provide fast access to an element or a mapping. For example, a character-to-ASCII mapping can use a character's ASCII value as an index and store its corresponding element there.
- Machine learning: Neural networks make extensive use of linear algebra on vectors, matrices, and tensors, all built from arrays. Arrays are the most common data structure in neural network programming.
- Implementing data structures: Arrays can implement stacks, queues, hash tables, heaps, graphs, and more. A graph's adjacency matrix, for example, is a two-dimensional array.