Back to Benchmark

Binary Search - O(log n) Complexity

Understanding how binary search achieves logarithmic time complexity through divide and conquer

What is Binary Search?

Binary search is an efficient algorithm for finding an item in a sorted array. It works by repeatedly dividing the search space in half, eliminating half of the remaining elements at each step.

Key Requirements:

  • Array must be sorted (ascending or descending)
  • Works on any ordered data structure (arrays, lists, etc.)
  • Much faster than linear search for large datasets

Think of it like searching for a word in a dictionary - you don't start from page 1. Instead, you open to the middle, see if your word comes before or after, and eliminate half the book. Repeat until found!

How Does Binary Search Work?

1. Start with the Middle

Compare the target value with the middle element of the array.

2. Eliminate Half

If the target is smaller, search the left half. If larger, search the right half. You've eliminated half the elements!

3. Repeat Until Found

Repeat the process on the remaining half until you find the element or determine it doesn't exist.

⚠️ Important: Array Must Be Sorted!

Binary search only works on sorted arrays. If the array isn't sorted, you must sort it first (O(n log n)) or use linear search (O(n)).

Interactive Binary Search Visualization
Try searching for a value in the sorted array below to see how binary search works step by step!

Code Example:

// Binary search implementation
function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);

    if (arr[mid] === target) {
      return mid;
    }

    if (arr[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return -1; // Not found
}
Built-in Functions for Binary Search
Many programming languages provide built-in functions that use binary search internally

Why is Binary Search O(log n)?

1. Divide and Conquer

At each step, binary search eliminates half of the remaining elements. This is the key to its efficiency!

2. Logarithmic Growth

The number of steps needed grows logarithmically with the array size:

Array size 8 → max 3 steps (log₂(8) = 3)
Array size 16 → max 4 steps (log₂(16) = 4)
Array size 32 → max 5 steps (log₂(32) = 5)
Array size 1,000,000 → max 20 steps!

3. Comparison with Linear Search

Linear search (O(n)) vs Binary search (O(log n)):

For 1,000,000 elements:
• Linear search: up to 1,000,000 steps
• Binary search: up to 20 steps
50,000x faster!
Sorting and Searching
Binary search requires a sorted array. Here's how sorting and searching work together

When to Sort First?

One-time search: If you only need to search once, linear search (O(n)) is better than sorting (O(n log n)) + binary search (O(log n)).

Multiple searches: If you need to search many times, sort once (O(n log n)) then use binary search (O(log n) per search). After k searches, total cost: O(n log n + k log n). For k > n, this is better than k linear searches (O(kn)).

Common Sorting Algorithms

O(n log n) - Efficient
• Quicksort, Mergesort, Heapsort
• Use these for large datasets
O(n²) - Simple but slow
• Bubble sort, Insertion sort, Selection sort
• Only for small datasets or learning

Search Algorithm Comparison

AlgorithmTime ComplexityRequirements
Linear SearchO(n)No requirements
Binary SearchO(log n)Array must be sorted
Hash Map LookupO(1)Hash map must be built first
Time Complexity Comparison
OperationBinary SearchLinear SearchExplanation
Search (sorted)O(log n)O(n)Binary search eliminates half at each step
Search (unsorted)N/AO(n)Must use linear search or sort first
Worst CaseO(log n)O(n)Binary search always O(log n), linear search worst case O(n)
Real-World Examples

📚 Dictionary Lookup

When looking up a word in a dictionary, you don't start from page 1. You open to the middle, see if your word comes before or after, and eliminate half the book. This is exactly binary search!

🔍 Database Indexing

Databases use binary search on sorted indexes to quickly find records. This is why indexed columns are so much faster for queries!

🎮 Game High Scores

When inserting a new high score into a sorted leaderboard, binary search finds the correct position quickly, even with thousands of scores.

📊 Finding Ranges

Binary search can find the first/last occurrence of a value, or find all values in a range. Useful for time-series data, logs, and sorted datasets.

Key Takeaways
  • Binary search is O(log n) - extremely efficient

    For large datasets, binary search is much faster than linear search

  • Requires sorted array

    The array must be sorted for binary search to work correctly

  • Divide and conquer approach

    Eliminates half the search space at each step, leading to logarithmic time complexity

  • Best for multiple searches

    If you need to search many times, sort once then use binary search for each query

Practice Exercises
Test your understanding of binary search with these exercises. Try to solve them yourself before checking the answers!