M12 · Searching

Jump, Exponential and Interpolation Search

Binary search is not the only way to use sorted order. Jump search skips ahead in blocks, exponential search finds a range by doubling before it bisects, and interpolation search guesses where a value should be from the values themselves. Each wins in a specific situation and loses in others; this lesson shows which, with exact read counts.

~35 minIntermediateC# · Python · Java · C++
Curriculum: M12 Searching · 3 of 3 lessons available

You will be able to

  • Trace jump search, exponential search and interpolation search on a sorted array and say which elements each read rules out.
  • Derive the √n block size for jump search from the cost n/m + m.
  • Explain why exponential search costs O(log i) for a target at position i, and when that beats plain binary search.
  • State the expected O(log log n) cost of interpolation search, the uniform-distribution assumption behind it, and build an input that makes it O(n).
  • Return the first occurrence with each method, and avoid the overflow and division-by-zero traps in interpolation search.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

Binary search uses sorted order in one particular way: look at the middle, discard half. Three other strategies use the same order differently:

  • Jump search walks forward in big strides, looking only at the last element of each block, and steps back into the one block that can contain the target.
  • Exponential search (also called galloping or doubling search) checks positions 1, 2, 4, 8, … until it overshoots, then binary-searches the last gap.
  • Interpolation search does not look at the middle at all. It estimates where the target should be from the values at the two ends of the range, the way you open a phone book near the back for "W".

All three need the array sorted in ascending order and, like binary search, give wrong answers rather than errors when it is not. The lab rejects unsorted input.

To make the three directly comparable, every version on this page returns the first index whose value equals the target, or −1, exactly like the lower-bound version of binary search. The lab counts element reads: each values[i] access is one read, and the four implementations below access the array in exactly the same places (their tests count reads through a wrapper).

m = ⌊√n⌋                         # block size
low = 0, high = min(m, n) − 1    # first block
while values[high] < target:     # whole block smaller: skip it
    low = high + 1
    if low ≥ n: return −1
    high = min(high + m, n − 1)
i = low
while values[i] < target: i += 1 # stops at high at the latest
return i if values[i] == target else −1

Why it is correct. When the loop moves past a block, its last element is smaller than the target, so every element in it is smaller (sorted order). When it stops, values[high] ≥ target, so the first element that is not smaller than the target lies in [low, high]. The forward scan finds that element; it is the first occurrence if it equals the target, and proof of absence if it does not. Run the Jump: blocks of √n preset: with 16 values the blocks have 4 elements, the block ends 12 and 45 are skipped, 77 stops the jumping, and the scan finds 72.

Why √n. With block size m, the worst case reads about n/m block ends and then up to m elements inside a block, so the cost is roughly

f(m) = n/m + m

The derivative −n/m² + 1 is zero at m = √n, which gives f(√n) = 2√n. Smaller blocks mean more jumps; bigger blocks mean a longer scan. For n = 1,000,000 that is about 2,000 reads, against about 20 for binary search and up to a million for a linear scan.

Reads (worst case) Extra space
Linear search n O(1)
Jump search, m = √n about 2√n O(1)
Binary search ⌊log₂ n⌋ + 1 O(1)

So on an array in memory, jump search is strictly worse than binary search. It is worth knowing for the situations where binary search's access pattern is the problem: data you can only move through forward, or where going back is expensive (a tape, a compressed stream, a sorted linked list with skip pointers every m nodes), it moves backwards at most once, by less than one block. That property, not its read count, is the reason it exists.

The teaching version reads the element where the scan stops twice (once in the loop test, once in the final check) to keep the code short; the Element reads metric counts both. Keeping it in a local variable would save that one read.

low = 0, bound = 1
while bound < n and values[bound] < target:
    low = bound + 1            # everything up to bound is smaller
    bound = min(2 · bound, n)
# the first copy, if any, is in [low, bound]: lower-bound binary search
high = bound
while low < high:
    mid = low + (high − low) / 2
    if values[mid] < target: low = mid + 1
    else:                    high = mid
return low if low < n and values[low] == target else −1

The doubling phase finds a range that must contain the answer; the second phase is exactly the lower-bound loop from the binary search lesson. Run Exponential: target near the front: in 64 values, the bounds 1, 2, 4 and 8 are read, 16 > 10 stops the doubling, and the binary search covers only [5, 8).

The cost depends on where the target is, not on n. If the answer is at index i, doubling stops after about log₂ i steps, and the final range has fewer than i elements, so the binary search takes about log₂ i more. Total: O(log i), which is never worse than O(log n) (i ≤ n) and much better when the target is near the front.

That makes it the natural choice in two situations:

  • Unbounded or unknown-length input: a sorted stream, an API that answers "value at position k" without telling you the length, or a function over the integers that is monotone. Binary search needs an upper end; exponential search finds one. This is the problem Bentley and Yao studied in 1976 (see the references).
  • Targets that are usually close: merging two sorted runs where most elements come from one side. Python's list sort (Timsort) and Java's object sort use exactly this "galloping" mode for that reason.

bound = min(2 · bound, n) needs care in fixed-width integers: 2 · bound overflows int when bound is above about a billion. The listings write it as bound <= n / 2 ? bound * 2 : n, which gives the same value and never overflows.

Binary search always probes the middle, no matter what the values are. If you are looking for 900 in values spread evenly from 0 to 1,000, the middle is a poor guess; position 90 % of the way along is a good one. Interpolation search computes that position:

pos = low + (target − values[low]) · (high − low) / (values[high] − values[low])

It is the point where the straight line from (low, values[low]) to (high, values[high]) reaches the target. The full loop:

low = 0, high = n − 1
while low ≤ high:
    lo = values[low], hi = values[high]
    if target < lo or target > hi: return −1     # outside the range: absent
    if lo == hi: return low                      # all candidates equal the target
    pos = low + (target − lo) · (high − low) / (hi − lo)
    if values[pos] < target:   low = pos + 1
    elif values[pos] > target: high = pos − 1
    else:
        while pos > low and values[pos − 1] == target: pos −= 1
        return pos
return −1

Three details are easy to get wrong:

  • The range check comes first. It guarantees lo ≤ target ≤ hi, which keeps pos inside [low, high]. Without it, a target outside the range produces a position outside the array.
  • Division by zero. When values[low] == values[high] the denominator is zero. Given the range check, the target then equals every candidate, so low is the answer.
  • Overflow. (target − lo) · (high − low) can exceed 32 bits even when every value fits in an int: the difference of two int values can reach about 4.3 billion, times an index range of millions. C#, Java and C++ compute it in 64 bits (long, std::int64_t); Python integers never overflow. The tests run every method on int.MinValue … int.MaxValue to check.

First occurrence. A hit at pos proves only that pos holds the target. Every index left of low is known to be smaller, so the version here walks left from pos while the previous element is also the target, never going below low. That costs one read per extra copy: fine for a few duplicates, linear if there are many. (The Interpolation: walk left preset shows it. A lower-bound style variant that keeps narrowing exists but needs extra care to guarantee progress, because the interpolated position can equal high forever.)

How fast is it, honestly?

  • Expected O(log log n), if the keys are drawn independently and uniformly at random from an interval. Each probe then shrinks the expected range to about its square root, and n → √n → ⁴√n … reaches 1 after about log₂ log₂ n steps: 5 for a million keys, versus 20 for binary search. Perl, Itai and Avni proved this in 1978.
  • Worst case O(n). When the values are far from a straight line, the guesses are bad, and each probe may rule out only one element. Run Interpolation: skewed values: 1 … 63 followed by 999. The huge last value drags every guess to the far left, the search creeps right one or two slots per probe, and it reads 126 elements to find 63, where binary search needs 6 iterations.
  • On evenly spaced keys it is almost magic: Interpolation: evenly spread finds the target with its first probe.

Each probe also costs more than a binary-search probe: a multiplication, a division and two extra reads, against one addition and a shift. On data in memory that often cancels the advantage, so the method pays off mainly when a probe is expensive (a disk page, a network request) and the keys are known to be close to uniform, such as sequential IDs, timestamps at a steady rate, or hash values.

Choosing between them

Method Reads Assumptions Use when
Linear search O(n) none unsorted data, tiny arrays
Binary search O(log n) sorted, random access the default for sorted arrays
Jump search O(√n) sorted; cheap forward moves stepping back is expensive
Exponential search O(log i) sorted unknown length, target near the front, galloping merges
Interpolation search O(log log n) expected, O(n) worst sorted, numeric, roughly uniform expensive probes on evenly spread keys

The linear search lesson covers the unsorted case.

What the standard libraries provide

None of C#, Python, Java or C++ ships jump search or interpolation search. What they do provide is a well-tested binary search, which is what you should normally use:

Language First position ≥ target Notes
C# Array.BinarySearch, List<T>.BinarySearch returns any match, or ~insertionPoint
Python bisect.bisect_left(a, x) the lower bound directly; key= since 3.10
Java Arrays.binarySearch, Collections.binarySearch any match, or -(insertionPoint) - 1
C++ std::lower_bound, std::ranges::lower_bound, std::partition_point the lower bound directly

Exponential search is easy to build on top of them: double a bound yourself, then call the library's binary search on the final range (bisect_left(a, x, lo, hi), Array.BinarySearch(a, index, length, x), Arrays.binarySearch(a, from, to, x), std::lower_bound(first + lo, first + hi, x)).

The teaching implementation

The three functions are written the same way in all four languages so the lab can highlight the matching lines. C# and Java take an IReadOnlyList<int> / List<Integer> and C++ any sequence with size() and operator[] (a std::span<const int> by default), so the tests can wrap the array and count reads; for production code you would take an array or span directly. Jump search uses (int)Math.Sqrt(n) in C# and Java, math.isqrt in Python and std::sqrt in C++, which all give ⌊√n⌋ for any array size. The C++ interpolation search uses signed std::ptrdiff_t indices because high starts at −1 for an empty sequence.

Every language runs one shared fixture (empty, one element, first, last, missing, smaller and larger than everything, duplicates, a short last block, evenly spread and skewed keys) and checks the exact read count of each method, then compares all three methods with a first-occurrence reference on 2,000 random sorted arrays with duplicates.

Common mistakes

  • Using these on unsorted data. As with binary search, the result is silently wrong.
  • Jump search: scanning the wrong block. The block to scan is the first whose last element is ≥ the target, not the last block whose first element is ≤ the target; with duplicates the second rule can miss earlier copies in the previous block.
  • Jump search: forgetting the short last block. high must be clipped to n − 1.
  • Exponential search: starting the binary search at 0. Correct but wasteful; everything up to the previous bound is already known to be smaller.
  • Interpolation search without the range check, without the lo == hi guard, or with 32-bit arithmetic in the position formula.
  • Calling interpolation search O(log log n) without "expected" and "uniformly distributed".

Edge cases

  • Empty array: −1 with no reads (jump and exponential return immediately; interpolation never enters its loop because high = −1).
  • One element: jump reads it as the block end, then scans and checks it; exponential skips doubling (bound = 1 = n) and binary-searches [0, 1); interpolation reads both ends (the same element).
  • Target larger than everything: jump runs off the end after ⌈n/m⌉ block reads; exponential doubles until bound = n; interpolation's range check rejects it at once.
  • Target smaller than everything: jump stops at the first block end and its scan stops at index 0; interpolation rejects it at once.
  • All elements equal: interpolation's lo == hi guard returns index 0 without dividing.

Worked practice

1. How many block ends does jump search read at most on 100 elements, and how many reads in total in the worst case?

Answer

m = ⌊√100⌋ = 10, so at most 10 block ends. In the worst case it then scans up to 10 elements and checks the last one once more: about 10 + 10 + 1 = 21 reads (the teaching version's final check is one extra read). Binary search needs at most ⌊log₂ 100⌋ + 1 = 7.

2. Exponential search for a value at index 1,000 in an array of a billion elements: roughly how many reads?

Answer

Doubling reads positions 1, 2, 4, …, 1024: about 11 reads. The final range [513, 1024] has 512 elements, so the binary search takes about 9 more, plus the final check: about 21 reads in total. Plain binary search over a billion elements needs about 30. The gap grows the closer the target is to the front.

3. In [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], where does interpolation search probe first for 70?

Answer

pos = 0 + (70 − 10) · (9 − 0) / (100 − 10) = 540 / 90 = 6, and values[6] = 70. One probe; the walk-left check reads values[5] = 60 and stops.

4. Build a sorted array of 8 values where interpolation search for the largest value probes more than 4 times.

Answer

Make the last value huge compared with the rest, e.g. [1, 2, 3, 4, 5, 6, 7, 999] and search for 7. Every guess lands near the left end (pos = low + (7 − lo) · (high − low) / (999 − lo) is close to low), so the search advances about one position per probe: 6 probes before the range check fails on the last step or the probe lands on 7. Binary search needs at most 4.

Summary

  • All three need sorted input; all three can return the first occurrence.
  • Jump search: blocks of √n, about 2√n reads; useful when moving backwards is expensive, not for arrays in memory.
  • Exponential search: O(log i) for a target at index i; the right tool for unbounded input and targets near the front, and the "galloping" inside Timsort.
  • Interpolation search: expected O(log log n) on uniformly distributed keys, O(n) worst case; guard the range, division by zero and overflow.
  • In practice, use your library's binary search (lower_bound, bisect_left, BinarySearch) and reach for these only when their assumptions match your data.

Full implementation

Jump, exponential and interpolation search in four languages, each checked against one shared fixture (empty, one element, first, last, missing, duplicates, a short last block, uniform and skewed keys) including the exact number of element reads per method, against 2,000 random sorted arrays with duplicates compared with a first-occurrence reference (Array.IndexOf, bisect_left, List.indexOf, std::lower_bound), and on int extremes to rule out overflow.

namespace Bekadan.Dsa.Examples.Searching;
 
/// <summary>
/// Jump, exponential and interpolation search over values sorted in ascending order.
/// All three return the index of the FIRST element equal to the target, or -1, and
/// none checks that the input is sorted. Each <c>values[i]</c> access is one read
/// (the tests count them through a wrapping <see cref="IReadOnlyList{T}"/>).
/// </summary>
public static class JumpExponentialSearch
{
    /// <summary>Blocks of floor(sqrt(n)): O(sqrt(n)) reads.</summary>
    public static int JumpSearch(IReadOnlyList<int> values, int target)
    {
        int n = values.Count;
        if (n == 0)
            return -1;
        int step = Math.Max(1, (int)Math.Sqrt(n)); // block size: floor(sqrt(n))
        int low = 0, high = Math.Min(step, n) - 1; // the first block is [low, high]
        while (values[high] < target) // the whole block is smaller: skip it
        {
            low = high + 1;
            if (low >= n)
                return -1; // every element is smaller than the target
            high = Math.Min(high + step, n - 1);
        }
        // values[high] >= target: the first copy, if any, is in [low, high].
        int i = low;
        while (values[i] < target) // stops by high at the latest
            i++;
        return values[i] == target ? i : -1;
    }
 
    /// <summary>Doubling bound, then a lower-bound binary search: O(log i) reads for an answer at index i.</summary>
    public static int ExponentialSearch(IReadOnlyList<int> values, int target)
    {
        int n = values.Count;
        if (n == 0)
            return -1;
        int low = 0, bound = 1;
        while (bound < n && values[bound] < target)
        {
            low = bound + 1; // everything up to bound is smaller
            bound = bound <= n / 2 ? bound * 2 : n; // min(2 * bound, n) without overflowing int
        }
        // The lower bound (first index with value >= target) is in [low, bound].
        int high = bound;
        while (low < high)
        {
            int mid = low + (high - low) / 2;
            if (values[mid] < target)
                low = mid + 1;
            else
                high = mid; // mid may be the answer: keep it
        }
        return low < n && values[low] == target ? low : -1;
    }
 
    /// <summary>Guesses the position by linear interpolation: O(log log n) expected on uniform keys, O(n) worst.</summary>
    public static int InterpolationSearch(IReadOnlyList<int> values, int target)
    {
        int low = 0, high = values.Count - 1;
        while (low <= high)
        {
            int lo = values[low], hi = values[high];
            if (target < lo || target > hi)
                return -1;
            if (lo == hi)
                return low; // every candidate equals the target; also avoids dividing by 0
            // 64-bit arithmetic: (target - lo) * (high - low) overflows int for large values.
            int pos = low + (int)(((long)target - lo) * (high - low) / ((long)hi - lo));
            int value = values[pos];
            if (value < target)
                low = pos + 1;
            else if (value > target)
                high = pos - 1;
            else
            {
                while (pos > low && values[pos - 1] == target)
                    pos--; // an earlier copy: the first one is further left
                return pos;
            }
        }
        return -1;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Searching/JumpExponentialSearch.cs

"""Jump, exponential and interpolation search on a sorted list.
 
All three return the index of the FIRST element equal to the target, or -1.
Each element is read through values[i] once per use; the tests count those
reads. None of them checks that the input is sorted.
 
- jump_search: O(sqrt n) reads with blocks of floor(sqrt n).
- exponential_search: O(log i) reads, where i is the position of the answer.
- interpolation_search: O(log log n) expected reads on uniformly distributed
  keys, O(n) in the worst case.
"""
 
import math
from collections.abc import Sequence
 
 
def jump_search(values: Sequence[int], target: int) -> int:
    n = len(values)
    if n == 0:
        return -1
    step = max(1, math.isqrt(n))  # block size: floor(sqrt(n))
    low, high = 0, min(step, n) - 1  # the first block is [low, high]
    while values[high] < target:  # the whole block is smaller: skip it
        low = high + 1
        if low >= n:
            return -1  # every element is smaller than the target
        high = min(high + step, n - 1)
    # values[high] >= target: the first copy, if any, is in [low, high].
    i = low
    while values[i] < target:  # stops by high at the latest
        i += 1
    return i if values[i] == target else -1
 
 
def exponential_search(values: Sequence[int], target: int) -> int:
    n = len(values)
    if n == 0:
        return -1
    low, bound = 0, 1
    while bound < n and values[bound] < target:
        low = bound + 1  # everything up to bound is smaller
        bound = min(bound * 2, n)
    # The lower bound (first index with value >= target) is in [low, bound].
    high = bound
    while low < high:
        mid = (low + high) // 2
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid  # mid may be the answer: keep it
    return low if low < n and values[low] == target else -1
 
 
def interpolation_search(values: Sequence[int], target: int) -> int:
    low, high = 0, len(values) - 1
    while low <= high:
        lo, hi = values[low], values[high]
        if target < lo or target > hi:
            return -1
        if lo == hi:
            return low  # every candidate equals the target; also avoids dividing by 0
        pos = low + (target - lo) * (high - low) // (hi - lo)
        value = values[pos]
        if value < target:
            low = pos + 1
        elif value > target:
            high = pos - 1
        else:
            while pos > low and values[pos - 1] == target:
                pos -= 1  # an earlier copy: the first one is further left
            return pos
    return -1

Tested on CPython 3.14.0 · examples/python/dsa_examples/jump_exponential_search.py

package dev.bekadan.dsa.searching;
 
import java.util.List;
 
/**
 * Jump, exponential and interpolation search over values sorted in ascending
 * order. All three return the index of the FIRST element equal to the target,
 * or -1, and none checks that the input is sorted. Each {@code values.get(i)}
 * is one read (the tests count them through a wrapping list). Pass a
 * random-access list such as {@code ArrayList} or {@code List.of}.
 */
public final class JumpExponentialSearch {
    private JumpExponentialSearch() {
    }
 
    /** Blocks of floor(sqrt(n)): O(sqrt(n)) reads. */
    public static int jumpSearch(List<Integer> values, int target) {
        int n = values.size();
        if (n == 0) {
            return -1;
        }
        int step = Math.max(1, (int) Math.sqrt(n)); // block size: floor(sqrt(n))
        int low = 0, high = Math.min(step, n) - 1; // the first block is [low, high]
        while (values.get(high) < target) { // the whole block is smaller: skip it
            low = high + 1;
            if (low >= n) {
                return -1; // every element is smaller than the target
            }
            high = Math.min(high + step, n - 1);
        }
        // values[high] >= target: the first copy, if any, is in [low, high].
        int i = low;
        while (values.get(i) < target) { // stops by high at the latest
            i++;
        }
        return values.get(i) == target ? i : -1;
    }
 
    /** Doubling bound, then a lower-bound binary search: O(log i) reads for an answer at index i. */
    public static int exponentialSearch(List<Integer> values, int target) {
        int n = values.size();
        if (n == 0) {
            return -1;
        }
        int low = 0, bound = 1;
        while (bound < n && values.get(bound) < target) {
            low = bound + 1; // everything up to bound is smaller
            bound = bound <= n / 2 ? bound * 2 : n; // min(2 * bound, n) without overflowing int
        }
        // The lower bound (first index with value >= target) is in [low, bound].
        int high = bound;
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (values.get(mid) < target) {
                low = mid + 1;
            } else {
                high = mid; // mid may be the answer: keep it
            }
        }
        return low < n && values.get(low) == target ? low : -1;
    }
 
    /** Guesses the position by linear interpolation: O(log log n) expected on uniform keys, O(n) worst. */
    public static int interpolationSearch(List<Integer> values, int target) {
        int low = 0, high = values.size() - 1;
        while (low <= high) {
            int lo = values.get(low), hi = values.get(high);
            if (target < lo || target > hi) {
                return -1;
            }
            if (lo == hi) {
                return low; // every candidate equals the target; also avoids dividing by 0
            }
            // 64-bit arithmetic: (target - lo) * (high - low) overflows int for large values.
            int pos = low + (int) (((long) target - lo) * (high - low) / ((long) hi - lo));
            int value = values.get(pos);
            if (value < target) {
                low = pos + 1;
            } else if (value > target) {
                high = pos - 1;
            } else {
                while (pos > low && values.get(pos - 1) == target) {
                    pos--; // an earlier copy: the first one is further left
                }
                return pos;
            }
        }
        return -1;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/searching/JumpExponentialSearch.java

#pragma once
 
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <span>
 
namespace bekadan::dsa {
 
// Jump, exponential and interpolation search over values sorted in ascending
// order. All three return the index of the FIRST element equal to the target,
// or -1, and none checks that the input is sorted. Each values[i] is one read
// (the tests count them through a wrapper). Values is any random-access
// sequence of int with size() and operator[](std::size_t), e.g. std::span<const int>.
 
// Blocks of floor(sqrt(n)): O(sqrt(n)) reads.
template <typename Values = std::span<const int>>
std::ptrdiff_t jump_search(const Values& values, int target) {
    const std::size_t n = values.size();
    if (n == 0) return -1;
    const std::size_t step = std::max<std::size_t>(1, static_cast<std::size_t>(std::sqrt(static_cast<double>(n))));
    std::size_t low = 0, high = std::min(step, n) - 1;  // the first block is [low, high]
    while (values[high] < target) {  // the whole block is smaller: skip it
        low = high + 1;
        if (low >= n) return -1;  // every element is smaller than the target
        high = std::min(high + step, n - 1);
    }
    // values[high] >= target: the first copy, if any, is in [low, high].
    std::size_t i = low;
    while (values[i] < target) ++i;  // stops by high at the latest
    return values[i] == target ? static_cast<std::ptrdiff_t>(i) : -1;
}
 
// Doubling bound, then a lower-bound binary search: O(log i) reads for an answer at index i.
template <typename Values = std::span<const int>>
std::ptrdiff_t exponential_search(const Values& values, int target) {
    const std::size_t n = values.size();
    if (n == 0) return -1;
    std::size_t low = 0, bound = 1;
    while (bound < n && values[bound] < target) {
        low = bound + 1;                         // everything up to bound is smaller
        bound = bound <= n / 2 ? bound * 2 : n;  // min(2 * bound, n) without overflow
    }
    // The lower bound (first index with value >= target) is in [low, bound].
    std::size_t high = bound;
    while (low < high) {
        const std::size_t mid = low + (high - low) / 2;
        if (values[mid] < target)
            low = mid + 1;
        else
            high = mid;  // mid may be the answer: keep it
    }
    return low < n && values[low] == target ? static_cast<std::ptrdiff_t>(low) : -1;
}
 
// Guesses the position by linear interpolation: O(log log n) expected on uniform keys, O(n) worst.
// Signed indices: high starts at -1 for an empty sequence.
template <typename Values = std::span<const int>>
std::ptrdiff_t interpolation_search(const Values& values, int target) {
    const auto at = [&values](std::ptrdiff_t i) { return values[static_cast<std::size_t>(i)]; };
    std::ptrdiff_t low = 0, high = static_cast<std::ptrdiff_t>(values.size()) - 1;
    while (low <= high) {
        const int lo = at(low), hi = at(high);
        if (target < lo || target > hi) return -1;
        if (lo == hi) return low;  // every candidate equals the target; also avoids dividing by 0
        // 64-bit arithmetic: (target - lo) * (high - low) overflows int for large values.
        std::ptrdiff_t pos = low + static_cast<std::ptrdiff_t>((std::int64_t{target} - lo) * (high - low) / (std::int64_t{hi} - lo));
        const int value = at(pos);
        if (value < target)
            low = pos + 1;
        else if (value > target)
            high = pos - 1;
        else {
            while (pos > low && at(pos - 1) == target) --pos;  // an earlier copy: the first one is further left
            return pos;
        }
    }
    return -1;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/jump_exponential_search.hpp

References