Exponential & Interpolation Search
Searching unbounded lists and uniform data, plus fractional cascading across many lists.
Binary search treats every sorted array alike, and that is its weakness as much as its strength. If the answer sits near the front, galloping finds it in probes, even in a list with no known end. If the keys are spread evenly, guessing where a key should be takes about probes: four or five for a million keys instead of twenty. And if you must search many lists for the same key, you can pay for one binary search instead of many.
What you’ll learn
- Analyze exponential (galloping) search, probes for an answer at position , and use it for unbounded search, uneven merges and Timsort's galloping mode.
- Prove with Kraft's inequality that every unbounded search algorithm needs more than questions for infinitely many , by viewing search strategies as prefix codes.
- Explain why interpolation search makes about expected probes on uniformly random keys, and construct inputs that force probes.
- Build a fractional-cascading structure that searches sorted lists of total size in time and space, and prove both bounds.
Galloping: pay for the distance, not the length
Binary search over spends about probes even when the answer is at index 3. Exponential search (also called galloping or doubling search) first probes indices until it overshoots, then binary searches the last gap. If the answer is at index , the doubling phase makes about probes and the binary search about more: , however long the array is, and without knowing at all.
def gallop(a, x):
"""First index i with a[i] >= x, in O(log i) probes; len(a) if there is none."""
n = len(a)
if n == 0 or a[0] >= x:
return 0
bound = 1
while bound < n and a[bound] < x: # invariant: a[bound // 2] < x
bound *= 2
lo, hi = bound // 2 + 1, min(bound, n) # the answer lies in [lo, hi]
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] < x:
lo = mid + 1
else:
hi = mid
return loTested against bisect_left. Counting probes, it never makes more than for an answer at index .
A sorted array has elements, and the lower bound of is index 100. About how many probes do gallop and plain binary search make?
- About 7 and 30
- About 15 and 30
- About 30 and 30
- About 100 and 30
Show the answer
B. About 15 and 30
After checking , doubling probes indices (8 probes) and stops at 128. The binary search over the candidates from 65 to 128 adds 6: 15 probes in all, . Binary search over elements needs .
Galloping pays off whenever answers sit close to a known position:
- Merging uneven lists. To merge keys into , gallop through the long list for each short-list key instead of comparing one by one. Hwang and Lin (1972) gave a merge with about comparisons, close to the information-theoretic minimum .
- Timsort's galloping mode. When one run keeps winning comparisons during a merge, Timsort switches to exponential search, so runs that barely interleave merge with far fewer than comparisons.
- Finger search. With a finger on position of a sorted array, or in a suitable search tree, a key at position is found in .
Near the end of the array, galloping costs about , twice binary search's price: it wins only when is well below .
Unbounded search and prefix codes
Strip galloping down to its core and you get the unbounded search problem of Bentley and Yao (1976): identify an unknown positive integer by asking questions "is ?". The questions you ask, and the order of the answers, turn out to be the same thing as a code for the integers, and that view gives both the best algorithms and a lower bound.
Doubling. Ask "?", "?", "?", …. The first yes, after questions, pins to with , and binary search over those candidates takes more:
Codes. Write the answers as bits, 1 for yes. A deterministic algorithm stops as soon as it knows , so no algorithm's answer sequence for one is a prefix of its sequence for another: every unbounded search algorithm is a prefix-free code for the positive integers, with codeword length . Doubling is exactly Elias's gamma code.
Better strategies. Find itself by doubling, then binary search within : that is Elias's delta code. Recursing further gives Bentley and Yao's family of algorithms, approaching up to lower-order terms.
Lower bound. Prefix codes obey Kraft's inequality. If an algorithm had for all large , its sum would include the tail of a divergent series:
So every unbounded search algorithm asks more than questions for infinitely many , and the same argument works with each further iterated logarithm. Bentley and Yao derived a lower bound of this kind showing that their algorithms are within lower-order terms of optimal, hence their title, An almost optimal algorithm for unbounded searching.
Interpolation search: guess where the key should be
Looking up "Mozart" in a printed phone book, you open it near the middle-back, not at the exact middle: you interpolate. If the keys are numbers spread evenly between and , the key should sit about here:
Fresh randomness. Given the current range, its inner keys are again independent and uniform between the two end values. The number of them below is binomial with mean , where is the relative position of in the interval, and the probe aims at that mean:
Square-root shrinking. So the probe typically lands within a few multiples of of the target. The full analyses turn this into an expected recurrence in which one probe cuts the range from candidates to :
Doubly logarithmic. Each probe roughly halves , so after probes about remains, and a constant range is reached after
def interpolation_search(a, x):
"""Index of x in the sorted list a of distinct integers, or -1."""
lo, hi = 0, len(a) - 1
while lo <= hi and a[lo] <= x <= a[hi]:
if a[hi] == a[lo]:
pos = lo
else: # integer arithmetic keeps the guess exact
pos = lo + (x - a[lo]) * (hi - lo) // (a[hi] - a[lo])
if a[pos] == x:
return pos
if a[pos] < x:
lo = pos + 1
else:
hi = pos - 1
return -1With keys drawn uniformly from , a test of this code averaged about 3.3 probes for and 4.3 for , matching ; binary search needs about 10 and 20.
Learned indexes push the idea further. Kraska and colleagues (2018) observed that predicting where a key sits in a sorted array is learning the cumulative distribution function of the keys, and replaced the top levels of B-trees with small models whose bounded prediction error a short local search then fixes. Interpolation search is the simplest such model: a straight line through the two ends of the range.
Fractional cascading: one search for k lists
You hold sorted lists with keys in total, and each query asks where a key belongs in every list. Separate binary searches cost . Fractional cascading (Chazelle & Guibas, 1986) answers in after linear-time preprocessing: the first search does the real work, and each further list costs . The trick is to copy a sample of each list into the one before it, so that a position found in one list points almost exactly at the position in the next.
BUILD(L1, ..., Lk): # every list ends with the sentinel +inf
M[k] <- Lk
for i <- k-1 down to 1:
M[i] <- MERGE(Li, every second key of M[i+1])
for each position p of M[i]: # filled in during the merge, in linear time
own[i][p] <- position in Li of the first key >= M[i][p]
bridge[i][p] <- position in M[i+1] of the first key >= M[i][p]
own[k][p] <- p for every p # M[k] is Lk itself
QUERY(x): # where x belongs in each list
p <- LOWER-BOUND(M[1], x) # the only binary search
for i <- 1 to k:
answer[i] <- own[i][p]
if i < k:
q <- bridge[i][p]
if q > 0 and M[i+1][q-1] >= x: q <- q - 1 # at most one step back
p <- q
return answerEach augmented list is plus every second key of . A Python version of this structure, tested on random lists against separate binary searches, never needed more than one step back.
Space. Each augmented list holds its own keys plus half of the next one: . Unrolling, the keys of contribute at most to , to , to , and so on:
One step back. Let be the first position of with key , so is correct: has no key in . The bridge is the first position of with key , and the true position , the first with key , satisfies . The keys at positions all lie in . Of any two consecutive positions of , one was copied into , and a copied key in would contradict the choice of . So
Query time. One binary search in , which has at most keys, then constant work per list:
Suppose each copies every fourth key of instead of every second. What happens to the bounds?
- Space grows to about , with still at most one step back
- Queries cost again
- Space shrinks to about , and a query may step back up to three positions per list
- The query becomes incorrect
Show the answer
C. Space shrinks to about , and a query may step back up to three positions per list
The geometric series becomes . Among any four consecutive positions of one is copied, so at most three keys can lie between the bridge and the true position. Any constant sampling rate gives space and time; the rate trades one constant against the other.
Chazelle and Guibas proved the general version, in which the lists hang on the nodes of any graph of bounded degree and a query walks a path of nodes. Applications include layered range trees, which answer 2-D orthogonal range queries in instead of , planar point location, and, in contests, the merge-sort tree, whose queries drop to with cascading.
Key takeaways
- Galloping finds an answer at position with at most probes and needs no length; it powers uneven merges, Timsort's galloping mode and finger search, and loses to binary search only near the end of an array.
- Unbounded search strategies are prefix codes for the integers: doubling is Elias's gamma code, and Kraft's inequality rules out questions for all large .
- Interpolation search averages about probes on uniformly random keys (about 4.3 for a million) but needs in the worst case; robust versions mix in binary steps, and learned indexes generalize the guess.
- Fractional cascading copies every second key of each list into the previous one, so one binary search plus work per list answers a query on lists: time in space.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
On an array of length , when does exponential search beat plain binary search by more than a constant factor?
- When the answer's index is small, so that is far smaller than
- Always: it never makes more probes than binary search
- When the keys are uniformly distributed
- When the array contains duplicates
Show the answer
A. When the answer's index is small, so that is far smaller than
Galloping costs about probes against for binary search, so it wins big when is tiny compared with and loses by up to a factor of 2 when the answer is near the end. Its other advantage is that it never needs .
Which statement about unbounded search (identify an unknown positive integer with questions "is ?") is true?
- Some algorithm asks only questions for every
- Doubling search is optimal up to an additive constant
- No algorithm asks at most questions for all large , because answer sequences form a prefix code and diverges
- The problem cannot be solved without an upper bound on
Show the answer
C. No algorithm asks at most questions for all large , because answer sequences form a prefix code and diverges
Answer sequences of a deterministic search form a prefix-free code, so . Lengths for all large would make that sum diverge.
Interpolation search runs on the 1,000 sorted keys . About how many probes does a search for 999 make?
- About 3, since
- About 10, like binary search
- About 999: every guess lands at the low end of the range and gains a single position
- 1: the formula computes the exact position
Show the answer
C. About 999: every guess lands at the low end of the range and gains a single position
The giant last key makes the formula place 999 near the start of the range at every step, so each probe removes one key: 999 probes, as running the code confirms. The bound is an average over uniformly random keys, not a worst-case guarantee.
With fractional cascading over sorted lists holding keys in total, which bounds hold?
- per query, space
- per query, space
- per query whatever is, space
- per query, but only with space
Show the answer
B. per query, space
Copying every second key of each augmented list into the one before it at most doubles the total size, and the bridges let each list after the first be searched with at most one step back: one binary search plus per list.
Further reading
- J. L. Bentley & A. C.-C. Yao, "An almost optimal algorithm for unbounded searching," Information Processing Letters 5(3) (1976), 82–87.
- Y. Perl, A. Itai & H. Avni, "Interpolation search—a log log N search," Communications of the ACM 21(7) (1978), 550–553.
- A. C. Yao & F. F. Yao, "The complexity of searching an ordered random table," Proceedings of the 17th IEEE Symposium on Foundations of Computer Science (1976), 173–177.
- B. Chazelle & L. J. Guibas, "Fractional cascading: I. A data structuring technique," Algorithmica 1 (1986), 133–162.
- F. K. Hwang & S. Lin, "A simple algorithm for merging two disjoint linearly ordered sets," SIAM Journal on Computing 1(1) (1972), 31–39.