Skip to main content

Command Palette

Search for a command to run...

Data Structure: Arrays

Updated
3 min read

Sometimes, an array is also called a list. Array organizes elements sequentially and in order. Data stored in the memory is one after another.

indexitem
0Oak
1Maple
2Pine
3Birch
4Cedar
5Palm
6Plum

Array Methods in JavaScript & Slice Functions in Go

有時候不同語言在操作array上,會有不同的時間複雜度或空間複雜度

JavaScript:

const example = ['a', 'b', 'c', 'd']
JavaScript MethodTime ComplexitySpace ComplexityExample Result
lookupexample[1]O(1)O(1)'a'
add an element to the end of the arrayexample.push('e')O(1)O(1)['a', 'b', 'c', 'd', 'e']
remove the last elementexample.pop()O(1)O(1)['a', 'b', 'c']
add an element at the beginning of the arrayexample.unshift('x')O(n) looping the array and reassigning the indexesO(n) looping the array and reassigning the indexes['x', 'a', 'b', 'c', 'd']
remove or add an element into any place of the arrayexample.splice(1, 0, 'pikachu')O(n) looping the array and reassigning the indexesO(n) looping the array and reassigning the indexes['a', 'pikachu', 'b', 'c', 'd']

Go:

example := []string{"a", "b", "c", "d"}
Go FunctionTime ComplexitySpace ComplexityExample Result
lookupget := example[1]O(1)O(1)"a"
add an element to the end of the arrayexample = append(example, "e")通常: O(1) / 需要擴充底層時: O(n)通常: O(1) / 需要擴充底層時: O(n)["a", "b", "c", "d", "e"]
remove the last elementexample = example[:len(example)-1]O(1)O(1)["a", "b", "c"]
add an element at the beginning of the arrayexample = append([]string{"x"}, example...)O(n) 需要建立一個新的slice並複製現有的elementsO(n) 需要建立一個新的slice並複製現有的elements["x", "a", "b", "c", "d"]
add an element into any place of the arraynewSlice := append(example[:1], append([]string{"pikachu"}, example[1:]...)...)O(n) 需要移動插入的點之後的所有elementsO(n) 需要移動插入的點之後的所有elements["a", "pikachu", "b", "c", "d"]

Two Type of Array: Static Array & Dynamic Array

Static Array

array的容量是固定的,每次要操作這個array時,都要符合他的大小限制,適合可預測資料量的情境。就像一個可以放六個布丁的箱子,硬要放七個布丁,就會有一個布丁放不進去

Time ComplexitySpace Complexity
lookupO(1)O(1)直接以index取得指定element
pushO(1)O(1)如果array還有空間,增加一個element在最後
insertO(n)O(n)如果array還有空間,在指定的index插入一個element,需要重新排序index
deleteO(n)O(n)刪除指定index的element,需要重新排序index

Dynamic Array

根據使用情境擴充array的容量,適合用在不確定資料量或需要經常變更資料量的情況,但擴充容量時可能會使影響效能

Time ComplexitySpace Complexity
lookupO(1)O(1)直接以index取得指定element
append通常: O(1)
需要擴充底層時: O(n)通常: O(1)
需要擴充底層時: O(n)增加一個element在最後
insertO(n)O(n)在指定的index插入一個element,需要重新排序index
deleteO(n)O(n)刪除指定index的element,需要重新排序index

Static Array V.S. Dynamic Array

兩種資料結構各有優缺點,實際選擇需要考量運用情境和業務考量,以及所使用的開發語言的特性

Static ArrayDynamic Array
效能insert & delete較快,因為不用考慮擴充的情況在需要擴充時,效能可能暫時下降,因為需要重新分配內存空間和複製現有elements
內存內存使用量固定且可預測,適合內存有限制的情況彈性大,較難預測內存使用量,通常會分配較多的內存空間,以因應資料量的增長
適用場景可預測資料量、內存受限且有高度效能需求不確定資料量或需要經常變更資料量
實現複雜度容易實現,但受限於內存容量不易使用,擴充時需要人為實現實現上較複雜,需要處理自動擴充的情境,但使用上較方便

Pros and Cons of Arrays

ProsCons
fast lookupslow insert
fast push/ popslow delete
data is orderedfixed size in static array

More from this blog