Static Arrays
Imagine you have a row of numbered boxes — like lockers at school. Each locker has a number on the door, and you can store exactly one thing inside.
That's all an array is. A row of boxes, each with a number, all lined up in order. Simple!
The boxes are called elements, and the numbers on them are called indexes (or indices). One important thing: computers start counting from 0, not 1. So the first box is box [0], the second is [1], and so on.
← → arrow keys to step · click elements to interact
Array Basics
Why can you find any box instantly?
Here's the magic trick: all the boxes are exactly the same size and sit right next to each other. That means the computer can do simple arithmetic to jump straight to any box.
Want box number 5? The computer thinks: "Box 0 is at the start. Each box is one step wide. So box 5 is exactly 5 steps from the start." One calculation, done. It never has to look at boxes 1, 2, 3, or 4 first.
This is why grabbing any item from an array is instant, no matter how big the array is.
Neighbours come free
When the computer fetches a box, it also quietly grabs the boxes sitting right next to it — because they're so close it's basically free. So if you look at box [0], boxes [1], [2], and [3] are already ready and waiting. This makes looping through an array very fast.
The one catch: fixed size
When you create an array, you decide exactly how many boxes you need. You can't add more later — the size is locked in. That's why it's called a static array ("static" means "doesn't change").
If you need 8 boxes, you get 8. If you only use 3 of them, the other 5 still take up space. And if you fill all 8 and need a 9th — tough luck, there's no room!
(The fix for that is a dynamic array, which we'll cover next.)
What searching looks like
Finding a specific value (not a box number) is slower. Say you want to find the number 55. The computer has to open box [0], check if it's 55 — nope. Open box [1] — nope. Keep going until it finds it. In the worst case it checks every single box.
Complexity
When should you use an array?
- You know exactly how many items you'll need
- You'll be grabbing items by their spot number a lot
- You want to loop through all of them quickly
- You don't need to change the size later
The one tradeoff
The fixed size is the big constraint. If you don't know how many items you'll end up with, check out the dynamic array — it's like an array that can grow when you need more room.
Linear Search
Quick check
Continue reading