An "array" is a linear data structure that operates as a lineup of similar items, stored together in a computer's memory in contiguous spaces. It's like a sequence that maintains organized storage. Each item in this lineup has its unique 'spot' known as an "index". Please refer to the Figure 4-1 to observe how arrays work and grasp these key terms.
Arrays can be initialized in two ways depending on the needs: either without initial values or with specified initial values. When initial values are not specified, most programming languages will set the array elements to \(0\):
/* Initialize array */vararr[5]int// In Go, specifying the length ([5]int) denotes an array, while not specifying it ([]int) denotes a slice.// Since Go's arrays are designed to have compile-time fixed length, only constants can be used to specify the length.// For convenience in implementing the extend() method, the Slice will be considered as an Array here.nums:=[]int{1,3,2,5,4}
Elements in an array are stored in contiguous memory spaces, making it simpler to compute each element's memory address. The formula shown in the Figure below aids in determining an element's memory address, utilizing the array's memory address (specifically, the first element's address) and the element's index. This computation streamlines direct access to the desired element.
Figure 4-2 Memory Address Calculation for Array Elements
As observed in the above illustration, array indexing conventionally begins at \(0\). While this might appear counterintuitive, considering counting usually starts at \(1\), within the address calculation formula, an index is essentially an offset from the memory address. For the first element's address, this offset is \(0\), validating its index as \(0\).
Accessing elements in an array is highly efficient, allowing us to randomly access any element in \(O(1)\) time.
Array elements are tightly packed in memory, with no space available to accommodate additional data between them. Illustrated in Figure below, inserting an element in the middle of an array requires shifting all subsequent elements back by one position to create room for the new element.
Figure 4-3 Array Element Insertion Example
It's important to note that due to the fixed length of an array, inserting an element will unavoidably result in the loss of the last element in the array. Solutions to address this issue will be explored in the "List" chapter.
array.py
definsert(nums:list[int],num:int,index:int):"""在数组的索引 index 处插入元素 num"""# 把索引 index 以及之后的所有元素向后移动一位foriinrange(len(nums)-1,index,-1):nums[i]=nums[i-1]# 将 num 赋给 index 处的元素nums[index]=num
array.cpp
/* 在数组的索引 index 处插入元素 num */voidinsert(int*nums,intsize,intnum,intindex){// 把索引 index 以及之后的所有元素向后移动一位for(inti=size-1;i>index;i--){nums[i]=nums[i-1];}// 将 num 赋给 index 处的元素nums[index]=num;}
array.java
/* 在数组的索引 index 处插入元素 num */voidinsert(int[]nums,intnum,intindex){// 把索引 index 以及之后的所有元素向后移动一位for(inti=nums.length-1;i>index;i--){nums[i]=nums[i-1];}// 将 num 赋给 index 处的元素nums[index]=num;}
array.cs
/* 在数组的索引 index 处插入元素 num */voidInsert(int[]nums,intnum,intindex){// 把索引 index 以及之后的所有元素向后移动一位for(inti=nums.Length-1;i>index;i--){nums[i]=nums[i-1];}// 将 num 赋给 index 处的元素nums[index]=num;}
array.go
/* 在数组的索引 index 处插入元素 num */funcinsert(nums[]int,numint,indexint){// 把索引 index 以及之后的所有元素向后移动一位fori:=len(nums)-1;i>index;i--{nums[i]=nums[i-1]}// 将 num 赋给 index 处的元素nums[index]=num}
array.swift
/* 在数组的索引 index 处插入元素 num */funcinsert(nums:inout[Int],num:Int,index:Int){// 把索引 index 以及之后的所有元素向后移动一位foriinnums.indices.dropFirst(index).reversed(){nums[i]=nums[i-1]}// 将 num 赋给 index 处的元素nums[index]=num}
array.js
/* 在数组的索引 index 处插入元素 num */functioninsert(nums,num,index){// 把索引 index 以及之后的所有元素向后移动一位for(leti=nums.length-1;i>index;i--){nums[i]=nums[i-1];}// 将 num 赋给 index 处的元素nums[index]=num;}
array.ts
/* 在数组的索引 index 处插入元素 num */functioninsert(nums:number[],num:number,index:number):void{// 把索引 index 以及之后的所有元素向后移动一位for(leti=nums.length-1;i>index;i--){nums[i]=nums[i-1];}// 将 num 赋给 index 处的元素nums[index]=num;}
array.dart
/* 在数组的索引 index 处插入元素 _num */voidinsert(List<int>nums,int_num,intindex){// 把索引 index 以及之后的所有元素向后移动一位for(vari=nums.length-1;i>index;i--){nums[i]=nums[i-1];}// 将 _num 赋给 index 处元素nums[index]=_num;}
array.rs
/* 在数组的索引 index 处插入元素 num */fninsert(nums: &mutVec<i32>,num: i32,index: usize){// 把索引 index 以及之后的所有元素向后移动一位foriin(index+1..nums.len()).rev(){nums[i]=nums[i-1];}// 将 num 赋给 index 处的元素nums[index]=num;}
array.c
/* 在数组的索引 index 处插入元素 num */voidinsert(int*nums,intsize,intnum,intindex){// 把索引 index 以及之后的所有元素向后移动一位for(inti=size-1;i>index;i--){nums[i]=nums[i-1];}// 将 num 赋给 index 处的元素nums[index]=num;}
array.kt
/* 在数组的索引 index 处插入元素 num */funinsert(nums:IntArray,num:Int,index:Int){// 把索引 index 以及之后的所有元素向后移动一位for(iinnums.size-1downToindex+1){nums[i]=nums[i-1]}// 将 num 赋给 index 处的元素nums[index]=num}
array.rb
### 在数组的索引 index 处插入元素 num ###definsert(nums,num,index)# 把索引 index 以及之后的所有元素向后移动一位foriin(nums.length-1).downto(index+1)nums[i]=nums[i-1]end# 将 num 赋给 index 处的元素nums[index]=numend
array.zig
// 在数组的索引 index 处插入元素 numfninsert(nums:[]i32,num:i32,index:usize)void{// 把索引 index 以及之后的所有元素向后移动一位vari=nums.len-1;while(i>index):(i-=1){nums[i]=nums[i-1];}// 将 num 赋给 index 处的元素nums[index]=num;}
Similarly, as depicted in the Figure 4-4 , to delete an element at index \(i\), all elements following index \(i\) must be moved forward by one position.
Figure 4-4 Array Element Deletion Example
Please note that after deletion, the former last element becomes "meaningless," hence requiring no specific modification.
array.py
defremove(nums:list[int],index:int):"""删除索引 index 处的元素"""# 把索引 index 之后的所有元素向前移动一位foriinrange(index,len(nums)-1):nums[i]=nums[i+1]
array.cpp
/* 删除索引 index 处的元素 */voidremove(int*nums,intsize,intindex){// 把索引 index 之后的所有元素向前移动一位for(inti=index;i<size-1;i++){nums[i]=nums[i+1];}}
array.java
/* 删除索引 index 处的元素 */voidremove(int[]nums,intindex){// 把索引 index 之后的所有元素向前移动一位for(inti=index;i<nums.length-1;i++){nums[i]=nums[i+1];}}
array.cs
/* 删除索引 index 处的元素 */voidRemove(int[]nums,intindex){// 把索引 index 之后的所有元素向前移动一位for(inti=index;i<nums.Length-1;i++){nums[i]=nums[i+1];}}
array.go
/* 删除索引 index 处的元素 */funcremove(nums[]int,indexint){// 把索引 index 之后的所有元素向前移动一位fori:=index;i<len(nums)-1;i++{nums[i]=nums[i+1]}}
array.swift
/* 删除索引 index 处的元素 */funcremove(nums:inout[Int],index:Int){// 把索引 index 之后的所有元素向前移动一位foriinnums.indices.dropFirst(index).dropLast(){nums[i]=nums[i+1]}}
array.js
/* 删除索引 index 处的元素 */functionremove(nums,index){// 把索引 index 之后的所有元素向前移动一位for(leti=index;i<nums.length-1;i++){nums[i]=nums[i+1];}}
array.ts
/* 删除索引 index 处的元素 */functionremove(nums:number[],index:number):void{// 把索引 index 之后的所有元素向前移动一位for(leti=index;i<nums.length-1;i++){nums[i]=nums[i+1];}}
array.dart
/* 删除索引 index 处的元素 */voidremove(List<int>nums,intindex){// 把索引 index 之后的所有元素向前移动一位for(vari=index;i<nums.length-1;i++){nums[i]=nums[i+1];}}
array.rs
/* 删除索引 index 处的元素 */fnremove(nums: &mutVec<i32>,index: usize){// 把索引 index 之后的所有元素向前移动一位foriinindex..nums.len()-1{nums[i]=nums[i+1];}}
array.c
/* 删除索引 index 处的元素 */// 注意:stdio.h 占用了 remove 关键词voidremoveItem(int*nums,intsize,intindex){// 把索引 index 之后的所有元素向前移动一位for(inti=index;i<size-1;i++){nums[i]=nums[i+1];}}
array.kt
/* 删除索引 index 处的元素 */funremove(nums:IntArray,index:Int){// 把索引 index 之后的所有元素向前移动一位for(iinindex..<nums.size-1){nums[i]=nums[i+1]}}
array.rb
### 删除索引 index 处的元素 ###defremove(nums,index)# 把索引 index 之后的所有元素向前移动一位foriinindex...nums.lengthnums[i]=nums[i+1]||0endend
array.zig
// 删除索引 index 处的元素fnremove(nums:[]i32,index:usize)void{// 把索引 index 之后的所有元素向前移动一位vari=index;while(i<nums.len-1):(i+=1){nums[i]=nums[i+1];}}
In summary, the insertion and deletion operations in arrays present the following disadvantages:
High Time Complexity: Both insertion and deletion in an array have an average time complexity of \(O(n)\), where \(n\) is the length of the array.
Loss of Elements: Due to the fixed length of arrays, elements that exceed the array's capacity are lost during insertion.
Waste of Memory: Initializing a longer array and utilizing only the front part results in "meaningless" end elements during insertion, leading to some wasted memory space.
In complex system environments, ensuring the availability of memory space after an array for safe capacity extension becomes challenging. Consequently, in most programming languages, the length of an array is immutable.
To expand an array, it's necessary to create a larger array and then copy the elements from the original array. This operation has a time complexity of \(O(n)\) and can be time-consuming for large arrays. The code are as follows:
Arrays are stored in contiguous memory spaces and consist of elements of the same type. This approach provides substantial prior information that systems can leverage to optimize the efficiency of data structure operations.
High Space Efficiency: Arrays allocate a contiguous block of memory for data, eliminating the need for additional structural overhead.
Support for Random Access: Arrays allow \(O(1)\) time access to any element.
Cache Locality: When accessing array elements, the computer not only loads them but also caches the surrounding data, utilizing high-speed cache to enchance subsequent operation speeds.
However, continuous space storage is a double-edged sword, with the following limitations:
Low Efficiency in Insertion and Deletion: As arrays accumulate many elements, inserting or deleting elements requires shifting a large number of elements.
Fixed Length: The length of an array is fixed after initialization. Expanding an array requires copying all data to a new array, incurring significant costs.
Space Wastage: If the allocated array size exceeds the what is necessary, the extra space is wasted.
Arrays are fundamental and widely used data structures. They find frequent application in various algorithms and serve in the implementation of complex data structures.
Random Access: Arrays are ideal for storing data when random sampling is required. By generating a random sequence based on indices, we can achieve random sampling efficiently.
Sorting and Searching: Arrays are the most commonly used data structure for sorting and searching algorithms. Techniques like quick sort, merge sort, binary search, etc., are primarily operate on arrays.
Lookup Tables: Arrays serve as efficient lookup tables for quick element or relationship retrieval. For instance, mapping characters to ASCII codes becomes seamless by using the ASCII code values as indices and storing corresponding elements in the array.
Machine Learning: Within the domain of neural networks, arrays play a pivotal role in executing crucial linear algebra operations involving vectors, matrices, and tensors. Arrays serve as the primary and most extensively used data structure in neural network programming.
Data Structure Implementation: Arrays serve as the building blocks for implementing various data structures like stacks, queues, hash tables, heaps, graphs, etc. For instance, the adjacency matrix representation of a graph is essentially a two-dimensional array.
Feel free to drop your insights, questions or suggestions