Data structures›Sorted arrays and binary search
Tutorial 7 of 13 · Data structures · Arrays and lists · BeginnerSorted arrays and binary search
Find a value in a sorted array by cutting the search in half, again and again.
6 lessons, the last is a challenge · about 1 h · Python and Java
Before you startArrays: you know what a cell and an index are, and you can read a cell by its index
You can write a few lines of Python or Java: variables, loops and functions
Watch first · about 8 minBinary search: thirty guesses for one number in a billion. The narration uses an AI clone of the creator’s voice.What you’ll be able to do
- 1Explain why halving finds a value in a sorted array so quickly, and say how many looks a thousand or a million items need.
- 2Follow lo, hi and mid through a binary search, and state the rule that keeps it correct, called its invariant.
- 3Spot the common traps: the wrong starting hi, a mid that stays in the range so the loop never ends, and the overflow in (lo + hi) / 2.
- 4Change the loop to find the first copy of a value or the place a missing value belongs, and search a sorted array that has been cut and swapped.
- 5Use bisect and Arrays.binarySearch, read what they return, and say when binary search is the right tool.
Lessons
Next in this path
Next: 8 · Recursion and the call stack · 6 lessons · 1 h 10 min
How a function solves a big job by calling itself on a smaller one.
Playground
Try the same model with your own values. No checks, nothing recorded.
Open the playground