1. Home
  2. Explore
  3. Computer Science
  4. Binary Search Algorithm

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Binary Search Algorithm

Binary Search

๐Ÿ” Introduction

Binary search is a fundamental algorithm for quickly locating a target value in a sorted array. At each step, it examines the middle element and eliminates half of the remaining search space. The concept is simple, but implementations are error-prone โ€” a 1988 study found that only one in four textbooks had a correct implementation. Even the Java standard library had an overflow bug that went unnoticed for over nine years.

Binary search works on any sorted sequence (numbers, words in a dictionary, etc.) where we can compare elements and decide which half to continue searching.


๐Ÿงฑ Basic Binary Search (Finding a Target Value)

Given a sorted array a of size n (indices 0 to n-1) and a target value, we want to find the index of the target, or return -1 if not present.

How it Works

  1. Maintain a search range [left, right] (initially [0, n-1]).

  2. Compute the middle index: mid = left + (right - left) / 2 (integer division, floor).

  3. Compare a[mid] with the target:

    • If equal, return mid.

    • If a[mid] < target, the target must be on the right โ†’ set left = mid + 1.

    • If a[mid] > target, the target must be on the left โ†’ set right = mid - 1.

  4. Repeat until left > right (range empty) โ†’ return -1.

Key property: The array must be sorted in non-decreasing order for this to work correctly.

Example

Array: [1, 4, 6, 8, 10, 12, 15], target = 10

  • Range [0,6], mid = 3 (a[3]=8 < 10) โ†’ go right: [4,6]

  • Range [4,6], mid = 5 (a[5]=12 > 10) โ†’ go left: [4,4]

  • Range [4,4], mid = 4 (a[4]=10 == 10) โ†’ return 4

If target = 9:

  • After narrowing, range becomes empty โ†’ return -1.


โš ๏ธ Implementation Pitfalls

Overflow in Middle Calculation

The naive formula mid = (left + right) / 2 can cause integer overflow when left and right are large (e.g., close to 231โˆ’12^{31} - 1231โˆ’1 in C++/Java int). The sum left + right may exceed the maximum representable value, leading to incorrect results.

Safe formula:
mid = left + (right - left) / 2

This works because right - left is always non-negative and fits in the same type (assuming right >= left).

Off-by-One Errors

Remember that when moving to a subrange, we exclude mid:

  • If target is on the right, new range is [mid+1, right].

  • If target is on the left, new range is [left, mid-1].

The loop condition left <= right ensures we continue until the range is empty.


๐Ÿงช Standard Binary Search Implementation (Pseudocode)

function binarySearch(a, n, target):
    left = 0
    right = n-1
    while left <= right:
        mid = left + (right - left) / 2   // integer division (floor)
        if a[mid] == target:
            return mid
        else if a[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

In C++/Java, the division truncates toward zero (for non-negative numbers, it's floor). In Python, use // for integer division.


โฑ Time Complexity

Each step halves the search range. In the worst case, we perform O(logโกn)O(\log n)O(logn) comparisons. The number of steps is roughly logโก2n\log_2 nlog2โ€‹n. Therefore, binary search has logarithmic time complexity: O(logโกn)O(\log n)O(logn).


๐Ÿงฉ Binary Search with Condition (Finding First/Last Satisfying Element)

Many problems ask for the first (or last) element that satisfies some condition, not necessarily equality. The classic example is the lower bound: find the first element โ‰ฅX\ge Xโ‰ฅX in a sorted array.

Approach with ans Variable

Instead of terminating when we find a match, we keep track of the best candidate so far. We continue searching for a better (smaller index) solution.

function lowerBound(a, n, X):
    left = 0
    right = n-1
    ans = -1   // or n (if returning index), or sentinel like INF
    while left <= right:
        mid = left + (right - left) / 2
        if a[mid] >= X:          // condition satisfied
            ans = mid            // record candidate
            right = mid - 1      // look for better (smaller) on left
        else:                    // condition not satisfied
            left = mid + 1       // look for answer on right
    return ans

Key idea: We treat the array as having a prefix of false and a suffix of true (or vice versa) for the condition. Binary search finds the boundary between the two halves.

  • If a[mid] satisfies the condition, it might be the answer, but there could be an earlier element โ†’ search left.

  • If a[mid] does not satisfy, the answer must be to the right โ†’ search right.

This pattern generalizes to many problems:

  • Find first true in a boolean-array that is [false..false, true..true].

  • Find last true in [true..true, false..false].

Example: Rotated Array โ€” Find Minimum Element

Problem: A sorted array is rotated (e.g., [6,7,9,15,19,2,3]). Find the smallest element in O(logโกn)O(\log n)O(logn) time.

Insight: Compare each element with the last element of the array. Elements greater than the last belong to the first (larger) part, elements smaller belong to the second (smaller) part.

Define condition: a[mid] > a[last]?

  • If true โ†’ mid is in the larger part โ†’ minimum is to its right โ†’ left = mid + 1.

  • If false โ†’ mid is in the smaller part (including minimum) โ†’ record as candidate and search left โ†’ ans = mid; right = mid - 1.

function findMinRotated(a):
    left = 0
    right = n-1
    ans = -1
    while left <= right:
        mid = left + (right - left) / 2
        if a[mid] > a[n-1]:          // condition: in larger part
            left = mid + 1
        else:                        // in smaller part
            ans = mid
            right = mid - 1
    return ans   // index of minimum

This works because the condition creates a prefix of true (larger part) and suffix of false (smaller part). We look for the first false.

Example: Peak Element (Mountain Array)

Problem: An array that strictly increases then strictly decreases (like a mountain). Find the index of the maximum element (peak).

Condition: a[mid] > a[mid-1]?

  • For the first element (index 0), we can treat as true (or add mid == 0 check).

  • True means we are on the increasing slope โ†’ peak might be to the right โ†’ ans = mid; left = mid + 1.

  • False means we are on the decreasing part โ†’ peak is to the left โ†’ right = mid - 1.

function findPeak(a):
    left = 0
    right = n-1
    ans = 0
    while left <= right:
        mid = left + (right - left) / 2
        if mid == 0 or a[mid] > a[mid-1]:   // condition: increasing
            ans = mid
            left = mid + 1
        else:
            right = mid - 1
    return ans

Here we look for the last true in a sequence that is true, ..., true, false, ..., false.


๐Ÿงฎ Binary Search on Real Numbers (Floating Point)

Binary search can find a value with a given precision (e.g., square root of XXX to within 10โˆ’910^{-9}10โˆ’9). The approach is similar, but since exact equality is rare, we stop when the interval is small enough.

Algorithm for Square Root of XXX

  • Range: [low, high] initially [0, X] (or [0, max(1, X)] for X < 1).

  • While high - low > epsilon:

    • mid = (low + high) / 2

    • If mid*mid < X โ†’ low = mid

    • Else โ†’ high = mid

  • Return mid (or (low+high)/2) as approximation.

Note: We do not use integer-style updates (low = mid+1) because numbers are continuous. Instead, we narrow the interval: low = mid or high = mid. This avoids missing the solution due to step size.

function sqrtReal(X, epsilon):
    low = 0
    high = max(1, X)
    while high - low > epsilon:
        mid = (low + high) / 2
        if mid*mid < X:
            low = mid
        else:
            high = mid
    return (low + high) / 2

Binary search on real values is often used for problems where the answer is a real number and we can check a condition (like "is this guess too small?").


๐Ÿ“ Summary

Type

Description

Key Difference from Basic

Basic Search

Find exact target in sorted array

Terminate on equality

First/Last Satisfying

Find first element that meets a condition

Use ans variable, continue search

Rotated Array Min

Find minimum in rotated sorted array

Condition: compare with last element

Peak Element

Find maximum in mountain array

Condition: compare with predecessor

Real-valued Search

Find value with given precision

Stop based on interval size, no exact equality

Core principle for advanced problems: Model the array as two parts (e.g., [false..false, true..true] or [true..true, false..false]). Ask about the middle element and decide which part might contain the boundary. Record possible answers and keep searching for better ones. This approach works whenever the array is monotonically non-decreasing with respect to some condition.

Understanding why we move left or right in each case โ€” not just memorizing steps โ€” is crucial for adapting binary search to new problems.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent