Log inStart free
LESSON 3.07 · 6 STAGES · 3 CONTROLS · 3 CHECKSPRO · PREVIEW

Searching and binary search

Watch binary search halve a sorted list and find 59 in 4 probes.


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 3 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 3.07 · SEARCH BAYLINEAR · 14 READS · FOUND AT 13
01
Stage 1 of 6 · Linear scan
A linear search reads the items one by one from the left. It finds 59 after 14 reads.
Explain it simply

Here are 16 numbers, smallest on the left. The small number under each box is its index, its place in the row. A linear search checks each box in turn, from the left. It needs 14 reads to reach 59. A list of a million could need a million.

The list: 3, 9, 13, 17, 23, 28, 34, 39, 42, 44, 50, 50, 50, 59, 62, 67. The target x is 59. A linear search reads 14 items and finds it at index 13.

list item, target xlo, hi and middropped itemanswer, probe countlinear reads, missed item
targetsorted list asearchesx = 593091132173234285346397428449501050115012591362146715linear14 readstargetsorted list asearchesx = 593091132173234285346397428449501050115012591362146715linear14 reads
Toy: 16 whole numbers · 3 targets · the loop of Python's bisect module · seeded
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
C={i+1if ai=xnif x is missing\sy{c}{grad}{C} = \begin{cases} \sy{i}{out}{i} + 1 & \text{if } \sy{a}{data}{a_i} = \sy{x}{data}{x} \\ \sy{n}{data}{n} & \text{if } \sy{x}{data}{x} \text{ is missing} \end{cases}
a13=59: C=13+1=14a_{13} = 59:\ \sy{c}{grad}{C} = 13 + 1 = 14

A linear search reads i + 1 items, or all n if x is missing.

Common mix-ups

MYTHBinary search works on any list of numbers.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q0118 is not in the list. What does bisect_left return?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 3 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.