Array, step by step.

An array is a data structure that stores elements of the same type in one contiguous block of memory, so any element is read by its index in O(1) time, while inserting or deleting anywhere but at the end shifts the elements after that position. A dynamic array also resizes itself when a value is added while it is full, by copying its elements into a larger array. This page explains how it works, with step-by-step animations of insertion, overwriting, deletion and dynamic array resizing from the VisiGrab app.

How an array works

What is an array in data structures?

An array is a data structure that stores elements of one type in one contiguous block of memory. Each element has an integer index, its position. All elements share one type, so an array is homogeneous. They form a sequence, so it is a linear data structure; trees, hash tables and graphs are non-linear. The app shows this split, then each part, step by step.

The array A drawn as a row of seven boxes holding 8, 5, 0, 1, 4, 9 and 3, outlined and labeled elements, with their indices 0 to 6 above them, outlined and labeled indices. A = stands before the row, and A[2] is written above index 2, over the 0.
Each element has an index, counted from 0: A[2] is the third element, 0.

Array indexing: why arrays start at 0

Square brackets select an element: A[2] is the element at index 2. Most languages use zero-based indexing: the first element is A[0], and the last of n elements is A[n − 1]. The index is an offset from the start of the array, so the first element is at offset 0. Fortran, MATLAB, Lua, R and Julia count from 1. Arrays give random access: any element is read directly, in any order, without passing the ones before it.

Assigning values to the elements is initialization. Until then, an array holds defaults, such as null or 0 in Java, or leftover values in a local C array. With only some values assigned, it is partially initialized.

Arrays in memory: why access by index is O(1)

An array takes one contiguous block of memory, starting at the base address. In an array of 4-byte integers, each element starts 4 bytes after the one before.

Memory drawn as a column of one-byte cells with their addresses. A[0] fills the four bytes from the base address 0x…1000 to 0x…1003, A[1] the four bytes from 0x…1004, and the elements continue in order.
Each integer takes 4 bytes, so A[i] starts at base + i × 4: A[1] at 0x…1004, A[2] at 0x…1008.

So the address of any element can be computed:

address of A[i] = base_address + i × element_size

With the base address 0x00001000 (0x…1000 in the figure), A[2] is at 0x00001000 + 2 × 4 = 0x00001008. One multiplication and one addition reach any element, so access by index takes O(1) time. Contiguous memory also gives cache locality: reading one element loads its neighbors into the cache.

Static vs dynamic array

A static array, or fixed-size array, gets its size at creation and keeps it. A dynamic array, or resizable array, grows as values are added. A static array suits a known count, such as the app's eight planets. For chat messages, too small an array goes out of bounds and too large a one wastes memory; the app shows both, step by step.

Note

In C and C++, "dynamic array" can also mean a heap array from new[] or malloc, which does not grow by itself.

Array index out of bounds

The valid indices of an array of size n are 0 to n − 1; any other index is out of bounds. Java throws ArrayIndexOutOfBoundsException, and Python raises IndexError: list index out of range. In Python, a[-1] is valid: it is the last element. C and C++ do not check plain arrays: the access is undefined behavior.

Size vs capacity of a dynamic array

A dynamic array usually stores its values in a static array, the underlying array, with spare slots. Its size is the number of elements in use, and its capacity the number of slots: the logical and the physical size.

How a dynamic array grows: resizing by doubling

Appending to a full dynamic array makes it resize: it allocates a new array a fixed factor larger, often twice as large, copies every element over, drops the old one and adds the value. In the player, e fills the last of five slots, and f makes the array resize: five copies into an array of capacity 10, then f goes in, and the size is 6.

Resize a dynamic array

All steps as text
  1. Let's look at a possible implementation of a dynamic array. It can be based on a static array.
  2. The dynamic array currently contains the following values: a, b, c and d. Suppose we want to add two more values.
  3. First, we add e. Under the hood it takes a free position in the static array.
  4. However, there is no room for f.
  5. When the static array is full and we want to add another value, a new array is created with twice the size.
  6. Then all values are copied into a new array.
  7. Finally, the old array is dropped and the value f is assigned to the next available position. Resizing is repeated each time the underlying array becomes full and a new value is added to it.
  8. The capacity doubled from 5 to 10, and size = 6: four more values fit before the next resize.
Resize a dynamic array. Last step: The capacity doubled from 5 to 10, and size = 6: four more values fit before the next resize.

Amortized analysis: why appending is O(1) amortized

In the worst case, one append costs O(n), because a resize copies all n elements. Doubling from capacity 1, an array of n elements has resized only about log2 n times: 8 doublings reach 256. When n is a power of 2, the copies cost 1 + 2 + 4 + … + n/2 = n − 1; for any n they cost less than 2n. So n appends cost O(n) in total, or O(1) each. This is the amortized cost: the average per operation over a worst-case sequence. Any growth factor above 1 gives it; adding a fixed number of slots does not. The app plots both costs on one graph.

Inserting into an array: shifting right

To insert at index i, every element from index i to the last one moves one slot right, last first: one move per element. A static array needs free space for the shift; a full one cannot take the value, but it can still overwrite one. A full dynamic array resizes first.

Two static arrays of five slots. Left: 4, 2, 0, 6 and a free slot; 2, 0 and 6 shift one slot right, 7 goes into index 1, and the result, 4, 7, 2, 0, 6, is marked as a success. Right: the full array 4, 7, 2, 0, 6, where inserting 9 fails because the array is full.
In a static array (Java, C++), inserting 7 at index 1 shifts 2, 0 and 6 one slot right; once the array is full, 9 cannot go in. A Python list would resize instead.

Inserting at the beginning moves every element. In the player, 99 goes into index 0 of 8, 5, 0, 1, 4, 9: the six values shift one slot right, last first, so none is overwritten, and then 99 is written.

Insert at the beginning

All steps as text
  1. A static array of 7 slots holds 8, 5, 0, 1, 4 and 9, and index 6 is free. Step forward to insert 99 at index 0.
  2. When a new value is inserted, the values of the elements on the right are shifted to the end of the array to make a space for the insertion.
  3. 4 moves right, from index 4 to 5.
  4. 1 moves right, from index 3 to 4.
  5. 0 moves right, from index 2 to 3.
  6. 5 moves right, from index 1 to 2.
  7. 8 moves right, from index 0 to 1.
  8. Index 0 is free now, so 99 is written there.
  9. The array reads 99, 8, 5, 0, 1, 4, 9 and is full. Inserting at the beginning moved all six values.
Array — Insert at the beginning. Last step: The array reads 99, 8, 5, 0, 1, 4, 9 and is full. Inserting at the beginning moved all six values.

Inserting at the end moves nothing: O(1), amortized for a dynamic array. The app also shows inserts and deletes at an arbitrary index.

Overwriting an array element

A full static array cannot take an insert, but it can still overwrite: A[i] = v replaces the value at index i in O(1), moves nothing and keeps the size, but the old value is lost. This is how a full array in Java or C++ changes its contents.

Note

A Python list is dynamic and never full, but a[i] = v replaces a value there too.

Here the array A, full with 8, 5, 0, 1, 4, 9 and 3, gets A[3] = 7: the 1 at index 3 is replaced.

Overwrite by index

All steps as text
  1. A holds 8, 5, 0, 1, 4, 9 and 3.
  2. A[3] is the element at index 3: it holds 1.
  3. A[3] = 7 writes 7 into index 3. The old value, 1, is gone.
  4. Nothing moved, and the size is still 7: an overwrite takes O(1).
Array — Overwrite by index. Last step: The array reads 8, 5, 0, 7, 4, 9, 3: the 7 at index 3 replaced the 1, and nothing else moved.

Deleting from an array: shifting left

Deleting leaves a gap, and no gaps are allowed, so every later element moves one slot left, first to last. In the player, 99 is deleted from index 0 of 99, 8, 5, 0, 1, 4, 9, and the other six values each move one slot left.

Delete from the beginning

All steps as text
  1. The array is full: 99, 8, 5, 0, 1, 4, 9. Step forward to delete 99 at index 0.
  2. When a value is deleted, the values of the elements on the right are shifted to the beginning of the array because no gaps are allowed in the array.
  3. 8 moves left, from index 1 to 0.
  4. 5 moves left, from index 2 to 1.
  5. 0 moves left, from index 3 to 2.
  6. 1 moves left, from index 4 to 3.
  7. 4 moves left, from index 5 to 4.
  8. 9 moves left, from index 6 to 5.
  9. The array reads 8, 5, 0, 1, 4, 9, and index 6 is free. Deleting from the beginning moved all six values.
Array — Delete from the beginning. Last step: The array reads 8, 5, 0, 1, 4, 9, and index 6 is free. Deleting from the beginning moved all six values.

Deleting the last element moves nothing: O(1). A dynamic array may also shrink when it gets sparse. Halving the capacity at exactly half full can thrash: alternating appends and deletes then resize every time. The usual rule halves it at a quarter full, which keeps deletion O(1) amortized. Java's ArrayList and C++'s std::vector never shrink on their own.

What is a dynamic array and how does it grow?

A dynamic array is an array that resizes itself as values are added. When its underlying array is full, an append allocates a larger one, twice as large in the app, and copies every value over. Resizes are rare enough that an append costs O(1) amortized.

Why is inserting at the beginning of an array slow?

Every element must first move one slot right to free index 0, so with n elements the insert makes n moves: O(n). The second player shows all six moves.

Array time complexity

OperationStatic arrayDynamic array
Access by indexO(1)O(1)
Overwrite by indexO(1)O(1)
Search, unsortedO(n)O(n)
Search, sorted (binary search)O(log n)O(log n)
Insert at the endO(1) if free space is availableO(1) amortized, O(n) worst case
Delete at the endO(1)O(1), amortized if it shrinks
Insert at the beginning or middleO(n) if free space is availableO(n)
Delete at the beginning or middleO(n)O(n)

Space is O(n); right after doubling, about half the slots are free.

Arrays in Python, Java and C++

Python's list, Java's ArrayList and C++'s std::vector are dynamic arrays. Java's int[] and C++'s std::array are fixed-size. Growth factors differ: about 1.125 in CPython, 1.5 in Java, and 2 in GCC and Clang but 1.5 in MSVC.

The full source code is on GitHub, in Python, Java and C++.

Array vs linked list

PropertyArrayLinked list
Access by indexO(1)O(n)
Insert or delete at the frontO(n)O(1)
MemoryThe values, plus any spare capacityEach value with one or two links
LayoutContiguous, cache-friendlyNodes scattered in memory

Arrays suit access by index and scans; linked lists suit frequent inserts and deletes at the front. In practice arrays often win even for inserts in the middle: shifting contiguous memory is faster than following links.

Note

In C and C++ a link is a pointer; in Java and Python it is a reference.

Multidimensional arrays: row-major and column-major order

A two-dimensional (2D) array is a grid, read as A[i][j]. C and C++ store it in row-major order, row after row: with c columns, A[i][j] is at base_address + (i × c + j) × element_size. Fortran and MATLAB use column-major order. In Java, a 2D array is an array of rows, which can differ in length: a jagged array. A graph's adjacency matrix is a two-dimensional array.

Where arrays are used: advantages and disadvantages

  • Strings, buffers, images and lookup tables.
  • A hash table: an array of buckets that grows by rehashing, much as a dynamic array does.
  • A min-heap, stored in an array with no links.
  • Sorting: bubble sort, selection sort, insertion sort and other in-place sorts rearrange an array's elements, and a sorted array allows binary search in O(log n).

Advantages: O(1) access by index, no per-element overhead and good cache use. Disadvantages: a static array has a fixed size, and inserts and deletes cost O(n) anywhere but the end.

6:27 Video Arrays Explained | Neo & Byte Ep. 0 Indexing from 0, static and dynamic arrays, and why inserting at the beginning is slow. Watch on YouTube

Four animations here.
The whole topic in the app.

In VisiGrab the array is a 58-slide show, from what an array is to dynamic arrays, played one step at a time.

Planets, messages, out of bounds

Why a static array suits the eight planets but not a chat: an index-out-of-bounds error, then a 1,000-slot array, most of it unused.

Amortized analysis, drawn

One graph shows the worst case, resizes growing as log n and the amortized O(1) line. Then deleting at the end, with and without halving.

Forward and back

Step through every slide and step back, or jump to any slide from the list. The show reopens where you left it.

Theory and complexity

Two tabs: Info, with the key characteristics, and Efficiency, with a complexity table for static and dynamic arrays. A tip shows an array in memory, byte by byte.

Python, Java and C++

Static arrays in Java and C++, Python's list, Java's ArrayList and C++'s std::vector, and a dynamic array built from scratch in Java and C++, explained part by part.

Quiz

Ten questions to check what you have learned before moving on.

Fill an array
slot by slot.

Download VisiGrab and step through indexing, resizing, shifting and amortized analysis yourself.

The array is one of 30+ topics. See them all