Binary Search by Hand

Binary search repeatedly uses sorted order to discard positions that cannot contain the desired value or boundary.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace an absent target
  2. Distinguish the returned result
  3. Trace the half-open candidate interval on an absent key
  4. Validate equality explicitly after finding the boundary

Trace an absent target

For sorted 2, 6, 9, 13 and target 8, using midpoint index two first compares 9. Search earlier offsets, then compare 6 at one. The first position with value at least eight is index two. Monotone predicates explain why the boundary remains meaningful even without an exact match.

Distinguish the returned result

A lookup can return missing because the insertion boundary holds 9. An insertion routine can return the same boundary as its solution. Loop invariants show how the half-open interval preserves that boundary.[1]

Trace the half-open candidate interval on an absent key

Find where nine could be inserted in [2, 5, 8, 12, 20, 23]. For a lower bound, an element below the target eliminates its position and every earlier position in range. An element at least the target lets you move the upper boundary down to the middle index. See ordered list search.

[0,6): middle 3 has 12, keep [0,3)
[0,3): middle 1 has 5, keep [2,3)
[2,3): middle 2 has 8, keep [3,3)
Insertion position 3; the exact key is absent

Validate equality explicitly after finding the boundary

A lower bound returning three tells you where nine would go. The element at that position is twelve. For a membership test, compare it to nine if the position is valid. Test a target above the largest key, which returns the length and offers no valid element to compare.

References

  1. Jeff Erickson, Algorithms ↩