Binary Search Algorithm

Master O(log n) search efficiency with interactive visualization. Watch how binary search eliminates half the search space with each comparison.

O(log n) Time
Sorted Array Required
Step Animation
Log n Speed
🎯
Divide & Conquer
📊
Visual Steps
💡
Code Examples
Powered by orbit2x.com

Binary Search Visualization

Live
Array Size: 0
Comparisons: 0
Target: -

Enter sorted array values to search

Binary search requires sorted input

Current Action:
Ready to search
Unsorted
Search Space
Midpoint
Eliminated
Found

Array Input & Search Controls

⚠️ Array must be sorted for binary search

O(log n) space

Code Implementation

def binary_search(arr, target):
    """
    Binary Search - Iterative Implementation
    Time: O(log n) - logarithmic time complexity
    Space: O(1) - constant space
    Prerequisite: Array must be sorted
    """
    left, right = 0, len(arr) - 1

    while left <= right:
        # Calculate midpoint (avoids overflow)
        mid = left + (right - left) // 2

        if arr[mid] == target:
            return mid  # Found at index mid
        elif target < arr[mid]:
            right = mid - 1  # Search left half
        else:
            left = mid + 1  # Search right half

    return -1  # Not found


def binary_search_recursive(arr, target, left, right):
    """
    Binary Search - Recursive Implementation
    Time: O(log n)
    Space: O(log n) - call stack depth
    """
    if left > right:
        return -1  # Base case: not found

    mid = left + (right - left) // 2

    if arr[mid] == target:
        return mid
    elif target < arr[mid]:
        return binary_search_recursive(arr, target, left, mid - 1)
    else:
        return binary_search_recursive(arr, target, mid + 1, right)


# Usage examples
arr = [2, 5, 8, 12, 16, 23, 38, 45, 56, 67, 78]
print(binary_search(arr, 23))  # Output: 5
print(binary_search(arr, 99))  # Output: -1

# Recursive version
print(binary_search_recursive(arr, 23, 0, len(arr)-1))  # Output: 5

Big O Complexity

Time O(log n)

Logarithmic time - halves search space

Space O(1)

Constant space - iterative method

Complexity Cases

Best Case O(1)

Target at exact midpoint - 1 comparison

Average Case O(log n)

Typical search - ⌈log₂n⌉ comparisons

Worst Case O(log n)

Not found or at boundary - max comparisons

Logarithmic
Eliminates half each step
📋
Sorted Required
Array must be sorted

Efficiency Example

Array Size: 1,000
Binary Search ~10 comparisons
Array Size: 1,000
Linear Search ~500 comparisons
50x faster! 🚀

💡 Key Insight

Binary search is exponentially faster than linear search. For 1 million elements, it needs only 20 comparisons vs 500,000 average for linear!

Real-World Applications

Binary search powers critical systems across technology - from databases to version control.

🗄️

Database Indexing

B-tree database indices use binary search principles for O(log n) lookups in sorted data. Foundation of SQL query optimization.

Billions of records
Millisecond queries
🔍

Git Bisect

Find bug-introducing commit by binary searching through commit history. Test midpoint, eliminate half based on result.

Debug efficiently
log₂n commits
📖

Dictionary Lookup

Phonebooks and dictionaries use binary search for fast lookups in alphabetically sorted entries.

Alphabetical search
Instant results
🌐

IP Routing Tables

Network routers use binary search on sorted IP ranges for fast packet routing decisions.

Longest prefix match
Nanosecond routing
⌨️

Auto-complete

Search engines and IDEs use binary search (lower bound) for finding prefix matches in sorted word lists.

Prefix matching
Real-time suggestions
💻

Coding Interviews

Binary search appears in 100+ LeetCode problems. Essential interview topic for software engineers.

LeetCode #704, #33, #34
Interview favorite

Why Binary Search Matters

For 1 million sorted elements, binary search needs only 20 comparisons while linear search averages 500,000. That's 25,000x faster!

O(log n)
Time Complexity
O(1)
Space (Iterative)
20
Max Comparisons (1M)

Binary Search Algorithm Tutorial: Master O(log n) Search in 2026

Learn binary search with interactive step-by-step visualization. Understand logarithmic time complexity, divide-and-conquer strategy, and why binary search is 25,000x faster than linear search for sorted arrays. Complete with code examples in Python, JavaScript, Java, C++, Go.

What Is Binary Search Algorithm (And Why Learn It)?

Binary search is a divide-and-conquer search algorithm that finds elements in sorted arrays with O(log n) time complexity. It works by repeatedly dividing the search space in half—checking the middle element, then eliminating half the remaining elements based on comparison. According to Wikipedia's Binary Search Analysis, this makes it exponentially faster than linear search for large datasets.

Binary search is fundamental to computer science and appears in 100+ LeetCode problems. It powers database indexing (B-trees), Git bisect debugging, dictionary lookups, IP routing tables, and auto-complete systems. For 1 million sorted elements, binary search needs only 20 comparisons vs 500,000 average for linear search—that's 25,000x faster!

Why Binary Search Is Essential for Programmers:

Technical Interview Must-Know
  • FAANG favorite: Asked at Google, Amazon, Facebook, Microsoft
  • 100+ LeetCode problems: Binary search on answer, rotated arrays, 2D matrices
  • Foundation for algorithms: Required for merge sort, quicksort understanding
  • Real system design: Database indexing, caching, load balancing
Performance Critical Skill
  • O(log n) efficiency: Scales to billions of records effortlessly
  • Production systems: Used in MySQL, PostgreSQL, MongoDB indexes
  • Algorithm optimization: Turns O(n²) problems into O(n log n)
  • Space efficient: O(1) space with iterative implementation

Binary Search vs Linear Search Example

Search for 67 in sorted array [2,5,8,12,16,23,38,45,56,67,78]:
❌ Linear Search: Check: 2,5,8,12,16,23,38,45,56,67
Comparisons: 10 (checks sequentially)
O(n) - Must scan all elements
✓ Binary Search: Check: 23 (mid) → 56 (mid) → 67
Comparisons: 3 (halves search space)
O(log n) - 3.3x faster here, 25,000x for 1M elements

How Binary Search Works: Step-by-Step Algorithm

1
Initialize left and right pointers: Set left = 0 (array start) and right = n-1 (array end). These pointers define the current search space. The entire sorted array is your initial search range for finding the target element.
2
Calculate midpoint: Find middle index using mid = left + (right - left) / 2. This formula prevents integer overflow (safer than (left + right) / 2). The midpoint element becomes your comparison pivot for eliminating half the search space each iteration.
3
Compare and eliminate: If arr[mid] == target, found! Return index. If target < arr[mid], set right = mid - 1 (search left half). If target > arr[mid], set left = mid + 1 (search right half). This guarantees you eliminate 50% of remaining elements every comparison—the secret to O(log n) efficiency.
4
Repeat until found or exhausted: Continue steps 2-3 while left <= right. When left > right, search space is empty—target doesn't exist. Return -1. Maximum iterations = ⌈log₂n⌉, so 1 billion elements needs only 30 comparisons!

💡 Binary Search Prerequisites

Critical requirement: Array MUST be sorted before applying binary search. Unsorted arrays require O(n log n) sorting first (use merge sort or quicksort). For frequently-searched data, sort once and reuse. For single searches on unsorted data, use linear search instead (O(n) vs O(n log n + log n)).

Understanding O(log n) Time Complexity

Binary search achieves logarithmic time complexity O(log n) because it halves the search space with each comparison. Logarithm base 2 (log₂) represents "how many times can I divide n by 2 until reaching 1?" This is the inverse of exponential growth—making binary search incredibly efficient even for massive datasets. Learn more about logarithmic complexity on Khan Academy.

Time Complexity Analysis:
Best Case: O(1) - Target at midpoint on first comparison (rare but possible)
Average Case: O(log n) - Target found after log₂n comparisons (typical scenario)
Worst Case: O(log n) - Target at boundary or not found (maximum ⌈log₂n⌉ comparisons)
Space Complexity Analysis:
Iterative: O(1) - Uses only left/right/mid variables (constant space)
Recursive: O(log n) - Call stack depth = max recursion levels (log₂n stack frames)

Logarithmic Growth Comparison

Array Size (n)Binary Search O(log n)Linear Search O(n)Speedup
10 elements4 comparisons5 comparisons1.25x
1,000 elements10 comparisons500 comparisons50x
1,000,000 elements20 comparisons500,000 comparisons25,000x
1,000,000,000 elements30 comparisons500,000,000 comparisons16,666,666x

8 Binary Search Variations You Must Know

1. Standard Binary Search (LeetCode #704)

Find exact target in sorted array. Returns index if found, -1 otherwise. Classic implementation taught in CS courses. Practice on LeetCode.

binary_search([1,3,5,7,9], target=5) → 2

2. Lower Bound (First Occurrence)

Find first occurrence of target in sorted array with duplicates. If target doesn't exist, returns insertion position. Used in C++ std::lower_bound, Python bisect_left.

lower_bound([1,2,2,2,5,7], target=2) → 1 (first 2)

3. Upper Bound (Last Occurrence)

Find last occurrence of target. Returns position after last occurrence. C++ std::upper_bound, Python bisect_right. Combine with lower bound for range queries.

upper_bound([1,2,2,2,5,7], target=2) → 4 (after last 2)

4. Search Insert Position (LeetCode #35)

Find index where target should be inserted to maintain sorted order. Perfect for maintaining sorted collections dynamically. Try LeetCode #35.

insert_position([1,3,5,7], target=4) → 2

5. Rotated Sorted Array Search (LeetCode #33)

Search in array rotated at unknown pivot: [4,5,6,7,0,1,2]. One half is always sorted—use binary search to identify sorted half, then decide which half to search. Amazon interview favorite. LeetCode #33.

6. Find Peak Element (LeetCode #162)

Find any peak where arr[i] > arr[i-1] and arr[i] > arr[i+1]. Binary search works on unsorted arrays here—compare mid with neighbors to decide direction. O(log n) solution for O(n) problem!

7. 2D Matrix Binary Search (LeetCode #74)

Search sorted 2D matrix where each row is sorted and first element of row[i+1] > last element of row[i]. Treat as 1D array: mid_val = matrix[mid/cols][mid%cols]. O(log(m×n)) complexity.

8. Binary Search on Answer

Advanced pattern: binary search the answer space rather than array. Example: "Find minimum capacity to ship packages within D days." Search capacity range [max(weights), sum(weights)] with feasibility check. Google/Facebook advanced interviews.

7 Real-World Binary Search Use Cases

1. Database Index Lookups (B-Tree Indexes)

MySQL, PostgreSQL, MongoDB use B-tree variants implementing binary search principles for O(log n) record retrieval. A table with 10 million rows needs only ~23 comparisons for indexed queries vs full table scan. This is why database indexes dramatically speed up SELECT queries. Learn more about DNS lookups which also use tree structures.

2. Git Bisect Debugging

git bisect uses binary search to find bug-introducing commits. Test commit at midpoint, mark good/bad, eliminate half the history. Find culprit commit in 1000+ commit history with only ~10 tests instead of 500+. Essential for large codebases and DevOps workflows.

3. IP Routing Table Lookups

Network routers maintain sorted IP ranges and binary search for longest prefix match (LPM) to route packets. Core routers handle millions of packets/second—binary search on sorted routing tables enables nanosecond routing decisions. Test IP lookups with our IP Address Lookup Tool.

4. Dictionary and Spell Check Systems

Digital dictionaries store words in sorted order and binary search for instant lookups. Spellcheckers find closest matches using binary search with edit distance. 470,000-word English dictionary searches complete in ~19 comparisons (log₂470000). This is how autocomplete and "Did you mean?" features work.

5. Auto-Complete and Prefix Matching

Search engines, IDEs, and mobile keyboards use binary search (lower bound) for finding prefix matches in sorted word lists. Type "bin" → binary search finds first word starting with "bin" in dictionary, display next N matches. Real-time suggestions with O(log n + k) complexity where k = number of results shown.

6. Load Balancing and Resource Allocation

Cloud platforms use binary search on answer for resource optimization: "What's minimum CPU cores needed to handle load?" Search feasible range, test midpoint configuration, eliminate half based on result. AWS, Azure, GCP auto-scaling algorithms leverage this for cost-efficient resource provisioning.

7. Version Control and Caching Systems

CDNs and caching layers maintain sorted timestamps for cache invalidation. Binary search finds which cache entries to purge based on time ranges. Git objects are stored with sorted SHA-1 hashes—binary search locates commits efficiently in large repositories. Critical for systems like GitHub with billions of commits.

7 Binary Search Implementation Mistakes That Break Code

1. Integer Overflow in Midpoint Calculation

Wrong: mid = (left + right) / 2 overflows when left+right > MAX_INT. Correct: mid = left + (right - left) / 2 prevents overflow for large arrays. This bug caused a 9-year binary search bug in Java's Arrays.binarySearch() (Google Research paper).

2. Incorrect Loop Termination Condition

Use while (left <= right) NOT while (left < right). Second version skips last element check when left==right, causing false negatives. The <= ensures you check all elements including boundaries.

3. Forgetting to Sort Array First

Binary search ONLY works on sorted arrays! Applying to unsorted data gives incorrect results—not errors, but wrong answers. Always verify sortedness or sort first with O(n log n) algorithms. Use our interactive tool to see why unsorted arrays fail.

4. Off-by-One Errors in Pointer Updates

After comparing mid: set right = mid - 1 or left = mid + 1—NOT right = mid. Without ±1, infinite loops occur when left==right==mid. The mid element was already checked, exclude it!

5. Not Handling Duplicates Correctly

Standard binary search returns any occurrence, not necessarily first or last. For duplicates, use lower_bound (first occurrence) or upper_bound (last occurrence) variants. LeetCode #34 "Find First and Last Position" tests this specifically.

6. Infinite Recursion in Recursive Implementation

Recursive binary search needs proper base case: if (left > right) return -1. Missing base case or incorrect pointer updates cause stack overflow. Iterative version avoids recursion overhead (O(1) space vs O(log n)).

7. Using Binary Search When Linear is Better

For tiny arrays (<10 elements), linear search overhead is lower due to simplicity and cache locality. For unsorted single-search scenarios, sorting costs O(n log n) + binary search O(log n) = O(n log n) total, worse than O(n) linear search. Choose wisely based on use case! Learn when to use linear search instead.

Binary Search Frequently Asked Questions (FAQ)

What is binary search and how does it work?

Binary search is a divide-and-conquer algorithm that searches sorted arrays by repeatedly halving the search space. It compares the target with the middle element: if equal, found; if target is smaller, search left half; if larger, search right half. This achieves O(log n) time complexity—for 1 million elements, only 20 comparisons needed vs 500,000 for linear search.

Why does binary search require a sorted array?

Binary search relies on comparison-based elimination: if target < mid, all elements > mid are discarded. This only works if array is sorted—unsorted arrays break this assumption, giving incorrect results (not errors, but wrong answers). Always sort first with O(n log n) algorithms like merge sort or quicksort, or use linear search for unsorted data.

What is the time complexity of binary search?

Best case: O(1) when target is at exact midpoint. Average/Worst case: O(log n) when target requires maximum ⌈log₂n⌉ comparisons. Space complexity: O(1) for iterative, O(log n) for recursive (call stack depth). This is why binary search scales to billions of elements—1 billion needs only 30 comparisons!

When should I use binary search vs linear search?

Use binary search: Large sorted arrays (>100 elements), repeated searches (sort once, search many times), when O(log n) efficiency matters. Use linear search: Small arrays (<10 elements), unsorted single-search scenarios, when sorting cost exceeds benefit. For unsorted data, linear search O(n) beats sort+binary O(n log n + log n). Test both with our linear search visualizer.

What are common binary search variations?

8 key variations: Standard (exact match), Lower bound (first occurrence), Upper bound (last occurrence), Insert position, Rotated sorted array, Peak element, 2D matrix search, Binary search on answer. Each has specific use cases—lower/upper bounds for duplicates, rotated array for pivoted data, search-on-answer for optimization problems. Master these for FAANG interviews.

How do I implement binary search in Python/JavaScript/Java?

See our interactive code examples above for 5 languages. Python: Use bisect module or implement manually. JavaScript: No built-in, implement with while loop. Java: Arrays.binarySearch() built-in. All follow same logic: left/right pointers, mid calculation left + (right-left)/2, eliminate half each iteration. Try live editor above for practice!

Is binary search used in real production systems?

Yes! Database indexes (MySQL B-trees use binary search principles), Git bisect (debugging commits), IP routing (longest prefix match), CDN caching (timestamp lookups), Auto-complete (prefix matching), Load balancers (resource allocation), File systems (sorted directory entries). Any system requiring fast sorted data lookup uses binary search variants. It's fundamental to computer science infrastructure.

What LeetCode problems should I practice for binary search?

Start with: LeetCode #704 (Binary Search), #35 (Search Insert Position), #34 (First and Last Position). Intermediate: #33 (Rotated Sorted Array), #162 (Peak Element), #74 (2D Matrix). Advanced: #875 (Koko Eating Bananas), #1011 (Capacity to Ship Packages)—"binary search on answer" pattern. 100+ total problems tagged binary-search on LeetCode.

Advanced Binary Search Interview Strategies

Template-Based Problem Solving

Master the 3 binary search templates: exact match, lower bound, upper bound. 95% of interview problems fit these patterns. Memorize template structure, then customize for specific problem constraints. This reduces debugging time by 80% in time-pressured interviews.

Recognizing Hidden Binary Search

Key indicators: "find minimum/maximum", "sorted/monotonic property", "optimize resource allocation". These signal binary search on answer. Ask: "Can I check if X is feasible in O(n)?" If yes + search space is ordered, binary search the answer space for O(n log k) solution.

Edge Case Testing

Always test: empty array [], single element [5], target at boundaries (first/last), target not found, all duplicates [3,3,3]. These catch 90% of implementation bugs. Walk through with interviewer before coding for bonus points and clarity.

Iterative vs Recursive Trade-Offs

Iterative: O(1) space, easier debugging, production preferred. Recursive: O(log n) space, cleaner code, easier for divide-conquer intuition. Mention both in interviews—write iterative, explain recursive for bonus. Some interviewers specifically ask for recursive version to test recursion understanding.

Optimization: Early Termination

Add checks before loop: if target < arr[0] or target > arr[n-1], return immediately. For duplicates finding range, if lower_bound result doesn't match target, upper_bound unnecessary. These optimizations show senior-level thinking in interviews.

Communicating Complexity Analysis

Explain: "Each iteration halves search space: n → n/2 → n/4 → ... → 1. Solving n/2^k = 1 gives k = log₂n iterations, so O(log n) time." Mention space complexity and trade-offs. This clarity in explanation often matters more than perfect code for senior roles.

Related Algorithm Learning Tools

Master algorithms and data structures with our complete interactive learning platform:

Ready to Master Binary Search Algorithm?

Start learning with interactive visualizations, step-by-step animations, and code examples in 5 languages. Perfect for technical interviews at Google, Amazon, Facebook, Microsoft. Understand O(log n) complexity with real-time demonstrations.

O(log n) Efficiency
100+ LeetCode Practice
5 Language Examples
FAANG Interview Ready

Trusted by 50,000+ developers preparing for technical interviews and mastering algorithms