Arrays
Six numbers in a row of memory: why reading any one of them is instant, why inserting in the middle is slow, and why an array cannot simply grow.
In 30 seconds
An array stores values in equal-sized slots, side by side in one block of memory. Each slot has an index, counted from 0.
Because the slots are equal and adjacent, the computer can calculate where any index lives and jump straight to it. That takes the same single step for an array of ten values or ten million.
The price is rigidity. Inserting or deleting in the middle means shifting everything after that point, and the block has a fixed size: to grow, the whole array is copied into a bigger one.
Arrays, step by step
Addresses are made up, and 4 bytes per number is one common size. O(1) and O(n) describe how the work grows with the number of values n.
- Step 1: A row of numbered slots. An array is a row of equal-sized slots, each holding one value. A slot is named by its index, its position in the row, counted from 0. This array has six slots, numbered 0 to 5, and five of them are filled.
- Step 2: One block of memory. In memory the slots sit side by side with no gaps: one contiguous block. Each number here takes 4 bytes, so the slots begin at addresses 1000, 1004, 1008 and so on. The memory on either side belongs to other things.
- Step 3: Jump to any index. Because the slots are equal and contiguous, the address of any slot is simple arithmetic: base + index × size. To read a[3] the computer works out 1012 and goes straight there. One step, whatever the length: constant time, written O(1).
- Step 4: Insert in the middle. To put 25 at index 1, every value from there onward must first move one slot to the right, starting from the end: 19, then 4, 30 and 7. That is four moves for one insert. With n values the work grows in step with n: linear time, O(n).
- Step 5: Delete in the middle. Deleting works the other way round. An array may not have a hole in it, so when the 7 at index 2 is removed, each value after it slides one slot to the left: 30, then 4, then 19. Three moves, and again O(n) in general.
- Step 6: Fixed size. Putting 8 into the last free slot is cheap: nothing has to move. But now all six slots are used, and the next value, 41, has nowhere to go. The memory just past the block is already taken, so an array cannot grow where it stands. Its size is fixed when it is created.
- Step 7: Growing means copying. To hold more, the program asks for a new, larger block somewhere else, here 12 slots at address 2000, copies all six values across, and gives the old block back. Then 41 fits. Growable lists do exactly this behind the scenes whenever they run out of room.
Try it yourself
Learn this first
Nothing. This concept starts from scratch.
Spotted a mistake on this page?