liveBook · Manning

Binary search

As explained in Julia as a Second Language

Binary search locates an element in an ordered collection by repeatedly comparing against the middle of a narrowing search range.

Binary search locates a value in a sorted array by repeatedly comparing it with the middle element and discarding the impossible half. Because each comparison narrows the range, it can find 18 in three comparisons instead of eight. section 13.2.1

The process is straightforward:

Searching a sorted Julia array

A = [2, 7, 9, 10, 11, 12, 15, 18, 19]\nsearchsorted(A, 18) # 8:8\nsearchsortedfirst(A, 18) # 8\nsearchsortedlast(A, 18) # 8\n\nThe array must remain sorted. Insertions can therefore require re-sorting, unlike set operations designed for membership checks. section 13.2.1

How Julia as a Second Language covers it

How deep it goes
Explains middle comparisons and range halving, then stops short of implementing the algorithm manually.
Examples
Demonstrates searching for 18 in a nine-element array using Julia's sorted-search functions.
What it assumes
Assumes familiarity with arrays and indices while establishing why sorted order enables range elimination.
What you can do after
Apply binary search through Julia's searchsorted functions on sorted arrays.
How it connects
Connects binary search with sorted arrays, sets, membership tests, and insertion costs.

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 Julia as a Second Language. The section links point to the parts of the book it draws on.