Algorithms And Data Structures Codexery

Binary search

Efficient search algorithm for sorted arrays.

Binary search

Binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array, eliminates the half in which the target cannot lie, and repeats this process until the target is found or the remaining half is empty. Binary search runs in logarithmic time in the worst case, making O(log n) comparisons, where n is the number of elements in the array.

field
Computer science
known_for
Search algorithm that finds the position of a target value within a sorted array
time_complexity
O(log n) in the worst case
data_structure_requirement
Sorted array

Lore & Background

Binary search works on sorted arrays by comparing an element in the middle of the array with the target value. If the target value matches the element, its position is returned. If the target value is less than the element, the search continues in the lower half; if greater, in the upper half. This eliminates the half where the target cannot lie in each iteration. The algorithm can be implemented iteratively, using variables L and R to track search boundaries, with the middle element m computed as L plus the floor of (R-L)/2.

Reader's Guide

Binary search is significant because it runs in logarithmic time, making it faster than linear search except for small arrays. However, the array must be sorted first to apply binary search. There are specialized data structures like hash tables that can be searched more efficiently, but binary search can solve a wider range of problems, such as finding the next-smallest or next-largest element in the array relative to the target even if it is absent. Variations include fractional cascading, which speeds up binary searches for the same value in multiple arrays, and exponential search, which extends binary search to unbounded lists. The binary search tree and B-tree data structures are based on binary search. Hermann Bottenbruch published the first implementation that leaves out the equality check during each iteration, resulting in a faster comparison loop.

Did You Know?

The Halving Principle

Binary search operates on a deceptively simple idea: by always examining the center of a sorted collection, you can discard half of the remaining candidates with every single comparison. The algorithm begins by positioning two boundary pointers, one at the start of the array and one at the end. It then calculates the midpoint, compares that element against the target value, and immediately throws away whichever half cannot possibly contain the answer. If the middle element is too small, the search shifts to the upper half; if too large, it retreats to the lower half. This elimination loop repeats, each iteration shrinking the search space by exactly half, until either the target is located or the remaining interval collapses to zero elements, signaling that the value simply does not exist in the array. The entire procedure is iterative, tracking only two variables, L and R, to maintain the active search window, making it both elegant and straightforward to implement without recursion.

Logarithmic Speed and Its Prerequisites

The defining performance characteristic of binary search is its logarithmic time complexity. In the worst case, the algorithm performs O(log n) comparisons, where n represents the total number of elements in the array. This means that even for arrays containing millions of entries, the search requires only a handful of steps, each one cutting the problem in half. For large datasets, this makes binary search dramatically faster than a linear scan, which must check elements one by one. However, this speed advantage only materializes once the array has already been sorted; the prerequisite of a pre-sorted sequence is the algorithm's most significant constraint. Additionally, for very small arrays, the overhead of computing midpoints and managing boundaries can make a simple linear search competitive or even preferable. And while specialized structures like hash tables can outperform binary search for exact-match lookups, binary search retains a broader utility that hash-based approaches do not always offer.

Beyond Exact Matches

One of binary search's most underappreciated strengths is its ability to solve problems that go well beyond locating an exact value. Even when the target is absent from the array, the algorithm naturally identifies the next-smallest or next-largest element relative to the target, making it a versatile tool for boundary-finding and approximate tasks. This generality sets it apart from lookup structures designed solely for exact matching, such as hash tables, which can outperform binary search for direct lookups but lack this broader problem-solving flexibility. The halving logic also serves as the conceptual foundation for several important data structures: binary search trees and B-trees both rely on the same principle of comparing against a central value and routing the search into the appropriate branch. These structures build upon the compare-and-eliminate principle, extending it into more complex organizational forms that support efficient searching in contexts where a single flat sorted array is insufficient.

Variations and Specialized Extensions

The core halving strategy of binary search has inspired a family of specialized variants tailored to different problem contexts. Fractional cascading, for instance, accelerates the task of searching for the same target value across multiple sorted arrays simultaneously, a technique that proves particularly powerful in computational geometry and numerous other fields where multi-array queries are common. Exponential search extends the binary search paradigm to unbounded lists, where the array has no known upper limit, by first expanding the search range before applying the standard halving procedure. These extensions demonstrate that the fundamental insight, compare, eliminate half, repeat, is not limited to a single fixed-size sorted array but can be adapted to handle dynamic or unbounded search spaces. Each variation preserves the logarithmic spirit of the original while addressing the specific constraints of its application domain, showing how one elegant principle can branch into a rich ecosystem of tools.

Frequently Asked Questions

Who is Binary search?

Binary search is a search algorithm in the Computer Science field that locates a target value inside a sorted array by repeatedly halving the search space. It is also known by the aliases half-interval search, logarithmic search, and binary chop.

What are Binary search's powers and role?

Its signature move is to compare the target against the middle element, discard the half where the target cannot reside, and repeat on the surviving half. This halving strategy yields a worst-case time complexity of O(log n) comparisons.

How does Binary search's story end?

The run concludes the moment the target matches an element or the remaining interval shrinks to zero, signaling the value is absent. Either way, the process wraps up after at most O(log n) iterations.

Why is Binary search important to the canon?

It is a cornerstone algorithm because it shows how a sorted structure enables lookups far faster than a linear scan. Its O(log n) performance makes it the default choice whenever an efficient search over a sorted array is needed.

What does Binary search need to function?

Its one hard requirement is that the input array be pre-sorted; without that ordering guarantee the halving logic collapses. It operates on a sorted array as its essential data-structure prerequisite.

More in Algorithms And Data Structures 1-24

Elsewhere in the Algorithms And Data Structures universe

Spotted an error? Know more?

This is a living reference — every entry is fact-audited, and reader corrections feed straight into our audit queue. Suggest an edit · See this site's audit record

Comments

Loading…
Open in the interactive codex →