Skip to content
Guest
Learn DSA · Course Syllabus Show lessons
Searching & Trees · 8 min read · Intermediate

Binary Search in O(log n)

Search sorted arrays of a million items in at most 20 comparisons using clean, bug-free Binary Search.

What you'll learn

  • Write overflow-safe midpoint calculation: lo + Math.floor((hi - lo) / 2)
  • Maintain strict loop invariants (lo <= hi) to avoid infinite loops
  • Understand why Binary Search requires a sorted or monotonic search space

Binary Search cuts the remaining search interval in half on every iteration. Even on 1,000,000 sorted elements, $\log_2(1,000,000) \approx 20$, so Binary Search finishes in at most 20 steps.

Fill-in-the-Blank Exercise

Binary Search Bounds Update

Narrow the left or right half based on comparing nums[mid] to target.

if (nums[mid] === target) return mid;
if (nums[mid] < target) lo = mid + ;
else hi = mid - ;

Live DSA Playground

O(log n) Binary Search
Live Result
Console Output

No console output yet. Try calling console.log(...) in JS.

Check Your Understanding

Score: 0 / 1

1. What precondition must hold for standard Binary Search to work on an array?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind