Searching

Problem shape

Beginner
4
8
15
16
23
42
Core idea

Compare the middle element, then discard the half that cannot contain the target.

Step 1 / 5
Problem shape
Current lesson

Binary Search Lab

Searching Beginner

Binary Search

Welcome to the Binary Search algorithm lab. Compare the middle element, then discard the half that cannot contain the target. Use it when: Use when the data is sorted and random access is available. The time complexity is O(log n), and the space complexity is O(1). The pseudocode is: low = 0, high = n - 1 while low <= high mid = (low + high) / 2 if a[mid] == target return mid if a[mid] < target low = mid + 1 else high = mid - 1 As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(log n)

Space

O(1)

Pseudocode

low = 0, high = n - 1
while low <= high
  mid = (low + high) / 2
  if a[mid] == target return mid
  if a[mid] < target low = mid + 1
  else high = mid - 1
Open deeper structure lesson
1.0x