Esc
  • Loading…
↑ ↓ to moveEnter to openEsc to close

Searching

Binary search and its many disguises across sorted and rotated structures.

  • 1 Lesson

Dry-run engine

Binary Search

A sorted array lets one read at the midpoint discard half of the remaining memory.

O(log n) Time
Input
arr = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], target = 23
Output · Returns
Press play to run it
How it works

Read mid = lo + (hi - lo) / 2. If arr[mid] < target, move lo = mid + 1; if it's greater, move hi = mid - 1. Every read halves the window.

sorted_ram_buffer[10]

  • lo0
  • hi9
  • mid4 (val: 16)
  • Compare16 < 23

lo=0, hi=9, so mid = 0 + (9 - 0) / 2 = 4, which holds 16. 16 < 23, so the target can only be to the right: discard [0..4] and set lo = 5.

1 / 3

Course Contents