%%🖋 Edit in Excalidraw, and the dark exported image%%

Properties

  • A data structure with a set length
  • Items are accessed via their index, which is a number that stores their location. They are usually 0-indexed, which means the index starts from 0 (instead of 1)
  • They are static (a fixed size) (not to be confused with static in OOP). Specifically, their length cannot be changed once initialised.
  • Items are added to arrays by overwriting previous value via index, or by swapping elements.

ADT Signature

name: Array
import: element,int,bool
ops:
	newArray: int → Array
	append: Array x element x int → Array
	get: Array x int  → element
	isEmpty/isFull: Array → bool
	length: Array → int

Time Complexity

The time complexity of an array varies depending on whether it is sorted or not.

Basic Operation: Array access

Assumptions:

  • = The array itself
  • = Elements in array
  • = Capacity (storage of the array)
  • : The index is a valid index.

To simplify analysis, we assume , i.e. we would never need to resize the array.

Terminology

Here, I use INSERT and DELETE to mean inserting and deleting by overwriting. That is, we are not changing the capacity of the array.

Unsorted
OperationOperation DescriptionWorst Case (WC)Average Case (AC)Best Case (BC)Case descriptions
GETAccess an element at index Basic operation
INSERTInsert an element at index , assuming there is space
WC (): Increase by 1, and set . Then insert the element by
setting
BC (): Inserting at index or higher involves no shifting
DELETEDelete an element at index (via overwriting )WC (): Swap the last element with , then decrement by 1
BC (): Decrement by 1.
SEARCHSearching for an element (assuming comparison is )WC ( or not in array): Have to Linear search through array
BC (): One comparison at the first element
AC (): See average case derivation
Sorted
OperationOperation DescriptionWorst Case (WC)Average Case (AC)Best Case (BC)Case descriptions
GETAccess an element at index Basic operation
INSERTInsert an element
WC ( is not the largest element) : Various methods exist:
1. Modified binary search that returns the index of greatest element lesser than ,
then shift all elements to right by 1, then insert.
2. Add to the end, then use insertion sort, which runs well when there are few unsorted elements.
BC ( is the largest element) : Insert at , increment after
DELETEDelete an element at index WC (): Need to shift elements to the right by one using element swaps.
BC (): Decrement by 1
SEARCHSearching for an element (assuming comparison is )See Binary Search Algorithm.

Worst case: , since it is equivalent to going to the lowermost level of a BST.

Implementation

Most Programming Languages store arrays as references to memory locations. That is, if we create an array, simply trying to assign it to something else will copy the reference, not the value:

In Java

#todo

{} is the syntax to for new int[] {3,3,5,5} creates a new unique array.