Binary search an unbounded range
Updated
Unbounded means you do not know n (or hi). You still need a closed interval before the log-shrink. Probe growing indices 1, 2, 4, 8, … until the value is past the target (or the probe falls off), then binary search that finite range.
What to focus on
Start at i=1. While the probe exists and a[i] < target, double i. The last failed probe and the first success bracket the answer. Tiny stream [1, 4, 9, …] target 9 uses probes at 1, 2, 4.
Worked examples
tiny stream
a = [1, 4, 9, ...] n unknown, target 9- probe i=1 → 4 < 9
- probe i=2 → 9
- probe i=4 would overshoot; binary search (1, 2]
Result: index 2
grow hi on integers
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], first m with m*m ≥ 9, hi unknown- probe 1 → 1 < 9
- probe 2 → 4 < 9
- probe 4 → 16 ≥ 9
- binary search 2..4
Result: m = 3
already past
a = [1, 4, 9, ...] n unknown, target 1- probe i=1 → 4 > 1
- range is [0, 1]
- binary search finds a[0]=1
Result: index 0
Try it
Write unboundedSearch(a, t). a is a non-decreasing stream whose length may be unknown. t is the target. Probe indices 1, 2, 4, … then L and R are indices of the finite range. Return the index (or m). [1, 4, 9, …] t=9 → probes 1, 2, 4 then index 2 First m with m*m ≥ 9 → probes 1, 2, 4 then m=3 [1, 4, 9, …] t=1 → range [0, 1], index 0
The stream is non-decreasing and non-empty. Target exists. A probe past the last legal index is reported as out of range. L, mid, and R are indices.