What?

A collection of elements, of the same memory size, individually identified by an index (usually starting with 0).

Why?

Best used for sequential and index-based element storage and lookup on a fixed number of elements. This is a very common requirement within applications handling data.

Good

  • Access: Sequentially apply f(element_at(i)) to each of n elements:
// unindexed
for each element in array:
	f(e)
// indexed
for i from 0 to length(array) - 1:
	f(array[i])
  • Access: Get the element at index i
array[i]
  • Update: Update element at i with value y
array[i] = y

Bad

  • Search: Find index i of element with value == x (for large values of n)

Ugly

The following operations are unsupported on a fixed-size array.

  • Insert: Insert an element x at position i
  • Remove: Remove an element x at position i

How?

Arrays are fixed size contiguous blocks of memory (from the perspective the application). With this underlying construction, accessing by index is essentially an efficient O(1) lookup operation in memory where:

element_at(array, index) = address_of(array) + index * size_of(element)

These types of operations are cache-friendly and therefore mechanically sympathetic due to pre-fetching or aligned data fetching in cache lines. Compilers detecting sequential access patterns applying pure functions may also be able to parallelize operations for improved performance.

Note: Since arrays are typically fixed-size on creation performing a lookup outside of the bounds of the array will either lead to undefined behavior, or in memory-safe languages will lead to an exception or panic.

Example(s):

Intermediate

Java: Simple

public class DS001 {
	public static void main(String [] args) {
		var array = new int[]{5, 42, 12, 9, 38};
		for (int element : array) {
			System.out.println(array[i]);
		}
		for (int element : array) {
			array[i] = array[i] + 1;
		}
		for (int element : array) {
			System.out.println(array[i]);
		}
	}
}
Compiled

Rust: Simple

fn main() {
    let mut array = [5, 42, 12, 9, 38];
    for element in array {
        println!("{}", element);
    }
    for i in 0..array.len() {
        array[i] = array[i] + 1;
    }
    for element in array {
        println!("{}", element);
    }
}

More

Learn and Practice