An array of letters from a to f with numbered indices 0 through 5.

Array

Other names:
static array

Quick reference

Worst Case
space
lookup
append
insert
delete

An array organizes items sequentially, one after another in memory.

Each position in the array has an index, starting at 0.

Strengths:

  • Fast lookups. Retrieving the element at a given index takes time, regardless of the length of the array.
  • Fast appends. Adding a new element at the end of the array takes time, if the array has space.

Weaknesses:

In Java

Here's what arrays look like in Java.

// instantiate an array that holds 10 integers int gasPrices[] = new int[10]; gasPrices[0] = 346; gasPrices[1] = 360; gasPrices[2] = 354;

Inserting

If we want to insert something into an array, first we have to make space by "scooting over" everything starting at the index we're inserting into:

An array of letters. From top to bottom, the values in the array are A, B, C, E, F, and G. The letter D is being inserted at the position of E, and the letters E, F, and G are each shown "scooting over" one index up to make room.

In the worst case we're inserting into the 0th index in the array (prepending), so we have to "scoot over" everything in the array. That's time.

Deleting

Array elements are stored adjacent to each other. So when we remove an element, we have to fill in the gap—"scooting over" all the elements that were after it:

Another array of letters. From top to bottom, the values in the array are A, B, C, Z, D, E, and F. The letter Z is being deleted, and the letters D, E, and F are each shown "scooting over" one index down to fill the space created by the deletion.

In the worst case we're deleting the 0th item in the array, so we have to "scoot over" everything else in the array. That's time.

Why not just leave the gap? Because the quick lookup power of arrays depends on everything being sequential and uninterrupted. This lets us predict exactly how far from the start of the array the 138th or 9,203rd item is. If there are gaps, we can no longer predict exactly where each array item will be.

Data structures built on arrays

Arrays are the building blocks for lots of other, more complex data structures.

Don't want to specify the size of your array ahead of time? One option: use a dynamic array.

Want to look up items by something other than an index? Use a hash map.

. . .