2
0
L
5
1
8
2
12
3
16
4
23
5
28
6
32
7
38
8
42
9
56
10
64
11
72
12
85
13
91
14
H
L (Low)0
H (High)14
M (Mid)?

The Master Detective

Binary Search is the detective of algorithms. It finds a target number (42) in a sorted list by always asking the middle person.

First Question

We start with the whole list (Low=0, High=14). We calculate the Middle: (0 + 14) / 2 = Index 7. VISUAL: The Rose Arrow points to 32.

Comparison

Is 32 the target (42)? No. Is it smaller or bigger? 32 is SMALLER than 42. This means our target must be to the RIGHT.

Ignore the Left

Since 32 was too small, everything to its left is also too small. We move Low to Mid + 1 (Index 8). The search space shrinks instantly!

Second Question

New Range: 8 to 14. Middle is (8 + 14) / 2 = Index 11. The value is 64.

Too Big!

64 is BIGGER than 42. So our target must be to the LEFT. We don't care about anything 64 or higher anymore.

Shrink Right

We move High to Mid - 1 (Index 10). Now we only care about Indices 8, 9, and 10. We are closing in!

Third Question

New Range: 8 to 10. Middle is (8 + 10) / 2 = Index 9. The value is 42.

Case Closed

Is 42 equal to 42? YES! We found it at Index 9. It only took 3 checks. A linear search would have taken 10 checks!

Efficiency Check

We found it in just 3 steps. Even if we had 1,000,000 items, it would only take about 20 steps! This is the power of O(log n).

Found it.

Binary Search is the backbone of efficient databases.

AlgoAnimator: Interactive Data Structures