liveBook · Manning

Binary search

As explained in Advanced Algorithms and Data Structures

Binary search is a search algorithm that repeatedly halves an ordered search range to locate a target or its insertion position.

Binary search locates a target or insertion position by repeatedly inspecting the middle of an ordered range and discarding the half that cannot contain the target. It works naturally on a sorted list, where each comparison determines whether to continue before or after the current position. section 4.4.2

Use binary search when the data is ordered, but account for the cost of maintaining that order:

  • Looking up an entry in a sorted array takes O(log(n)) time and requires no extra memory. section 4.4.2
  • Creating the sorted structure costs O(n*log(n)), while adding or removing an entry costs O(n) because elements may need to shift. section 2.3 section 4.4.2
  • A sorted list can suit infrequent updates and small datasets, but millions or billions of elements make repeated movement problematic. section 2.3

Searching a phone book

To find Bloom, open near the middle, compare the first surname with Bloom, and discard the region on the wrong side. Repeating this narrows the search between known lower and upper bounds. Sorting contacts first enables the same approach, but maintaining the sorted list makes additions expensive. section 4.4.2

Table 4.2 Using sorted arrays as dictionaries (view table figure)

Operation

Running time

Extra memory

Creating the structure

O(n*log(n))

O(n)

Looking up an entry

O(log(n))

No

Add a new entry

O(n)

No

Remove an entry

O(n)

No

Compare construction, lookup, insertion, and removal costs for sorted arrays used as dictionaries. section 4.4.2

The method is straightforward in one dimension: each value has an unambiguous left and right side. In higher-dimensional spaces, partitioning is harder because a simple vertical split can ignore other coordinates and separate nearby points poorly. section 8.4.1 section 8.4.2

How Advanced Algorithms and Data Structures covers it

How deep it goes
Explains midpoint partitioning, sorted-array costs, and one-dimensional limits, while stopping short of implementation pseudocode.
Examples
Uses a phone book, sorted contacts, corpus terms, and a sorted-array operation table.
What it assumes
Assumes ordered data and comparisons, while building the midpoint-halving intuition through a familiar phone-book search.
What you can do after
Apply binary search to ordered data and evaluate its lookup benefits against sorting and update costs.
How it connects
Connects sorted arrays, dictionaries, binary search trees, and nearest-neighbor search.

Also explained in

Compare how 7 books explain binary search →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Advanced Algorithms and Data Structures. The section links point to the parts of the book it draws on.