Exponential Search
Read indexes 1, 2, 4, 8, … until a value is not smaller than the target, then binary search the last bracket. The cost depends on where the target is, not on how long the list is.
How Exponential Search Works
- If a[0] is the target, return 0.
- Set i = 1. While a[i] is smaller than the target, double i.
- If a[i] equals the target, return i.
- Binary search the open range i/2 + 1 to i − 1, clamped to the end of the array.
Exponential search, also called galloping search or doubling search, works on sorted data in two phases. First it reads index 1, 2, 4, 8 and so on, doubling each time, until it reads a value that is not smaller than the target. The previous read was smaller, so the target can only lie between those two indexes. Then a binary search inside that bracket finds it.
On 3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80, searching for 69 reads 3, 7, 12, 21 and 42, all smaller, then index 16, which is past the end. The bracket is 9 to 15, and binary search there reads 64, 74 and 69: nine probes in all.
- The last read below the target gives the lower bound, the overshoot gives the upper
- The bracket is at most as wide as the target's distance from the start
- A read past the end counts as an overshoot
Searching a List with No Known End
Binary search needs both ends before it can pick a middle. Some sorted data has no end it can tell you: an API that returns the i-th record of a huge log, a file read in chunks, or the classic interview question of searching a sorted array of unknown size, where reading past the end returns a sentinel such as 2³¹ − 1.
Exponential search is the standard answer to this unbounded binary search problem. The doubling phase finds a finite upper bound in about log₂ k reads, where k is the target's index, and from then on an ordinary binary search takes over. The code on this page reads through a function that returns infinity past the end and never uses the length.
- Reading past the end must return something larger than any real value
- The length is never needed, only a way to read index i
- Also works for monotone functions, such as finding the first x with f(x) ≥ t
Exponential Search Time Complexity
If the target is at index k, the doubling phase stops after about log₂ k + 1 reads, and the bracket it leaves holds fewer than k indexes, so the binary search takes about log₂ k more. Exponential search therefore runs in O(log k) time, at most O(log n), with O(1) extra space for the iterative version.
This is a bound on the target's position, not on the list's length. With a million values and the target at index 10, exponential search needs 8 probes and binary search over the whole array 18. With the target near the end of a short list it loses: 69 at index 13 costs 9 probes against 3 for binary search that already knows n = 16.
| Case | Exponential | Binary (knows n) |
|---|---|---|
| 16 values, find 7 at index 1 | 2 | 3 |
| 16 values, find 69 at index 13 | 9 | 3 |
| 16 values, miss 50 | 9 | 4 |
| 1,000,000 values, find 30 at index 10 | 8 | 18 |
- O(log k): the cost follows the target's position
- About twice binary search's probes when the target is near the end
- Never worse than O(log n) overall
Terms, operations, and practical uses
Key terms
- BracketThe range between the last read below the target and the first read at or above it.
- GallopingTimsort's name for doubling ahead during a merge.
- Unbounded searchSearching sorted data whose length is unknown or infinite.
Related
- Binary searchThe second phase of exponential search.
- Jump searchFixed-size steps instead of doubling ones.
- Merge sortThe merge step that Timsort speeds up by galloping.
- First Bad VersionFind the first failing item in a sorted sequence.
Code in Python, C++ and Java
INF = float("inf")
nums = [3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80]
def make_reader(values):
return lambda i: values[i] if i < len(values) else INF
def exponential_search(get, target):
probes = 1
if get(0) == target:
return 0, probes
i = 1
while True:
probes += 1
v = get(i)
if v == target:
return i, probes
if v > target:
break
i *= 2
lo, hi = i // 2 + 1, i - 1
while lo <= hi:
mid = (lo + hi) // 2
probes += 1
v = get(mid)
if v == target:
return mid, probes
if v < target:
lo = mid + 1
else:
hi = mid - 1
return -1, probes
def binary_search(get, n, target):
lo, hi, probes = 0, n - 1, 0
while lo <= hi:
mid = (lo + hi) // 2
probes += 1
v = get(mid)
if v == target:
return mid, probes
if v < target:
lo = mid + 1
else:
hi = mid - 1
return -1, probes
get = make_reader(nums)
for target in (7, 69, 50):
i, p = exponential_search(get, target)
_, b = binary_search(get, len(nums), target)
print(f"find {target}: index {i}, exponential {p} probes, binary {b}")
big = lambda i: 3 * i if i < 1_000_000 else INF
i, p = exponential_search(big, 30)
_, b = binary_search(big, 1_000_000, 30)
print(f"1,000,000 values, find 30: index {i}, exponential {p} probes, binary {b}")#include <climits>
#include <functional>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
using Reader = function<long long(long long)>;
pair<long long, int> exponentialSearch(const Reader& get, long long target) {
int probes = 1;
if (get(0) == target) return {0, probes};
long long i = 1;
while (true) {
probes++;
long long v = get(i);
if (v == target) return {i, probes};
if (v > target) break;
i *= 2;
}
long long lo = i / 2 + 1, hi = i - 1;
while (lo <= hi) {
long long mid = lo + (hi - lo) / 2;
probes++;
long long v = get(mid);
if (v == target) return {mid, probes};
if (v < target) lo = mid + 1;
else hi = mid - 1;
}
return {-1, probes};
}
pair<long long, int> binarySearch(const Reader& get, long long n, long long target) {
long long lo = 0, hi = n - 1;
int probes = 0;
while (lo <= hi) {
long long mid = lo + (hi - lo) / 2;
probes++;
long long v = get(mid);
if (v == target) return {mid, probes};
if (v < target) lo = mid + 1;
else hi = mid - 1;
}
return {-1, probes};
}
int main() {
vector<long long> nums = {3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80};
Reader get = [&](long long i) { return i < (long long)nums.size() ? nums[i] : LLONG_MAX; };
for (long long target : {7, 69, 50}) {
auto [i, p] = exponentialSearch(get, target);
int b = binarySearch(get, nums.size(), target).second;
cout << "find " << target << ": index " << i << ", exponential " << p << " probes, binary " << b << "\n";
}
Reader big = [](long long i) { return i < 1000000 ? 3 * i : LLONG_MAX; };
auto [i, p] = exponentialSearch(big, 30);
int b = binarySearch(big, 1000000, 30).second;
cout << "1,000,000 values, find 30: index " << i << ", exponential " << p << " probes, binary " << b << "\n";
}import java.util.function.LongUnaryOperator;
public class Main {
static long[] exponentialSearch(LongUnaryOperator get, long target) {
int probes = 1;
if (get.applyAsLong(0) == target) return new long[]{0, probes};
long i = 1;
while (true) {
probes++;
long v = get.applyAsLong(i);
if (v == target) return new long[]{i, probes};
if (v > target) break;
i *= 2;
}
long lo = i / 2 + 1, hi = i - 1;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
probes++;
long v = get.applyAsLong(mid);
if (v == target) return new long[]{mid, probes};
if (v < target) lo = mid + 1;
else hi = mid - 1;
}
return new long[]{-1, probes};
}
static long[] binarySearch(LongUnaryOperator get, long n, long target) {
long lo = 0, hi = n - 1;
int probes = 0;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
probes++;
long v = get.applyAsLong(mid);
if (v == target) return new long[]{mid, probes};
if (v < target) lo = mid + 1;
else hi = mid - 1;
}
return new long[]{-1, probes};
}
public static void main(String[] args) {
long[] nums = {3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80};
LongUnaryOperator get = i -> i < nums.length ? nums[(int) i] : Long.MAX_VALUE;
for (long target : new long[]{7, 69, 50}) {
long[] r = exponentialSearch(get, target);
long b = binarySearch(get, nums.length, target)[1];
System.out.println("find " + target + ": index " + r[0] + ", exponential " + r[1] + " probes, binary " + b);
}
LongUnaryOperator big = i -> i < 1000000 ? 3 * i : Long.MAX_VALUE;
long[] r = exponentialSearch(big, 30);
long b = binarySearch(big, 1000000, 30)[1];
System.out.println("1,000,000 values, find 30: index " + r[0] + ", exponential " + r[1] + " probes, binary " + b);
}
}Step through it
Running on [3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80] · length unknown · target 69
Where It Is Used
Timsort, the sort behind Python's sorted() and Java's object sorts, uses galloping when merging two runs. If one run keeps winning, it stops comparing one element at a time and gallops: it checks 1, 2, 4, 8, … elements ahead to find how many to copy in one block, then binary searches the exact cut. On data with long sorted stretches this saves most of the comparisons.
The same doubling trick appears in searching a sorted stream, in finding the first failing version when the number of versions is unknown, and in binary search on the answer when there is no obvious upper limit for the answer: double a guess until it is big enough, then halve back.
- Timsort's galloping mode in merges
- Unknown-size arrays and sorted streams
- Finding an upper limit before a binary search on the answer
Edge Cases
Check a[0] first, since doubling starts at 1. Stop doubling when the index passes the end of a known-length array and clamp the bracket to n − 1; with a reader that returns infinity, the overshoot does this automatically. Double with care in fixed-width integers: i × 2 can overflow near the top of the int range, so use 64-bit indexes or stop before doubling past the limit.
- Test index 0 before doubling
- Clamp hi to n − 1 when the length is known
- Doubling an int index near 2³¹ overflows