AI Wiki中文/EN

Algorithms and complexity: count the whole computation

算法与复杂度

Prove lower-bound search, measure comparisons and separate preprocessing, worst-case, average and amortized costs.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Four comparisons can still sit inside a linear-time program

A monitoring service keeps sorted integer sensor readings. For each alert threshold, it wants the first reading that reaches it. One implementation walks from the beginning; another jumps to the middle and discards half the remaining range. On eight readings, the second version needs at most four value comparisons.

Now put a full “is this list sorted?” check inside every query. The answer still takes at most four search comparisons, but the wrapper examines all eight readings. As the list grows, that distinction dominates. Complexity analysis must name the operation being analyzed, the input size and the cost model before attaching a symbol such as O(log n).

This chapter implements both searches and counts their value comparisons. We will prove correctness, derive a worst-case bound, account for preparation and explain why neither a short program nor a good stopwatch result is a complexity proof.

Specify the problem before counting its work

A boundary, not just a matching element

Let a be a nondecreasing sequence of n integers. The lower-bound position for target x is the number of entries strictly smaller than x:

r(a,x)=∣{i:0≤i<n, ai<x}∣,0≤r≤n.r(a,x)=\left|\{i:0\le i<n,\ a_i<x\}\right|,\qquad 0\le r\le n.

All entries before r are smaller; every entry from r onward is at least x. If x occurs repeatedly, r is its first position. If every entry is smaller, the answer is n, a valid insertion position rather than a valid element index. For an empty sequence, it is zero. This is the partition contract of Python’s bisect_left.

A linear scan returns the first entry that fails the strict comparison. Binary search keeps a half-open unresolved interval [lo, hi). Its invariant says every index below lo has value smaller than x, and every index at or above hi has value at least x. The true boundary lies between lo and hi, inclusive.

At mid, a value smaller than x makes all positions through mid irrelevant, so set lo = mid + 1. Otherwise the boundary is no later than mid, so set hi = mid. Both changes preserve the invariant and strictly shrink the interval. When the endpoints meet, the boundary is known. Returning immediately on equality would not generally find the first duplicate.

Choose what one step means

Our counter increments for each comparison between a stored value and the query target. Preparation has a separate counter for adjacent-value comparisons. Loop conditions, integer index arithmetic, type checks, reference copying and output are not included in these counters. Under a word-RAM model, bounded-word arithmetic and indexed access have constant cost, so search time is proportional to one plus its comparison count. MIT’s models-of-computation notes make this choice of operations and costs explicit.

For nonnegative functions f and g, with g eventually positive, asymptotic upper and lower bounds mean:

f∈O(g)  ⟺  ∃c>0,n0 ∀n≥n0: f(n)≤cg(n),f∈Ω(g)  ⟺  ∃c>0,n0 ∀n≥n0: f(n)≥cg(n),Θ(g)=O(g)∩Ω(g).f\in O(g)\iff\exists c>0,n_0\ \forall n\ge n_0:\ f(n)\le cg(n),\qquad f\in\Omega(g)\iff\exists c>0,n_0\ \forall n\ge n_0:\ f(n)\ge cg(n),\qquad \Theta(g)=O(g)\cap\Omega(g).

O is an upper bound, not a synonym for “worst case.” First define whether f describes a particular input, the maximum over inputs of size n, or an expectation under a stated distribution. A linear function is also O(n squared), but that looser bound hides useful information. Theta states a matching growth order; it does not give a time in seconds.

The logarithm follows from shrinking the interval

For an interval of length n, the larger remaining interval has length at most floor(n/2). A target no greater than the minimum repeatedly takes that larger left branch. Consequently the exact worst number of value comparisons for this implementation is:

Cmax⁡(0)=0,Cmax⁡(n)=1+Cmax⁡(⌊n/2⌋)=⌊log⁡2n⌋+1=⌈log⁡2(n+1)⌉(n≥1).C_{\max}(0)=0,\qquad C_{\max}(n)=1+C_{\max}(\lfloor n/2\rfloor)=\lfloor\log_2 n\rfloor+1=\lceil\log_2(n+1)\rceil\quad(n\ge1).

The linear scan takes min(r+1,n) comparisons: one extra comparison after the entries below the target unless it reaches the end. Its worst count is n and, for nonempty input, its best is one. This binary implementation does not stop on equality; even its best case has logarithmic growth as n grows. A textbook search with a different stopping rule can have different best-case behavior.

The worst bound is also optimal within a particular model. For n distinct ordered values there are n+1 possible boundary answers. If a deterministic algorithm learns about the target only through Boolean order comparisons, a decision tree of depth h has at most 2 to the power h leaves. Thus some query needs at least ceiling(log base 2 of (n+1)) comparisons. This argument concerns the comparison model, not every possible representation or machine instruction; MIT’s searching lower-bound lecture explains that restriction.

Average and amortized costs answer different questions

An average requires a probability law. If the n+1 insertion ranks for eight distinct values are equally likely, the binary decision tree has two leaves at depth four and seven at depth three: mean 29/9 comparisons. The scan’s counts are 1 through 8 followed by another 8: mean 44/9. Uniform ranks are a chosen workload, not a consequence of “random data.”

Amortized analysis bounds an entire operation sequence without assuming random inputs. For a conceptual array that starts with capacity one and doubles whenever full, n appends cause copies at old capacities 1, 2, 4 and so on, each less than n. Those copies sum to less than 2n; adding n writes gives fewer than 3n element copies/writes for n at least one. One append can still cost linear time. This geometric argument underlies table-doubling analysis; it does not assert that CPython uses this exact doubling policy.

Count the search, then account for the wrapper

The Python 3.12 program accepts lists or tuples of integers, rejects Booleans and unsorted input, allows duplicates and emptiness, and takes an immutable tuple snapshot of the supplied sequence. Construction validates once. A later mutation of the original list cannot change the index. Ordinary attribute reassignment is blocked; this is an application contract, not protection against deliberate reflection.

search returns (position, comparisons) and does not copy or revalidate the entire sequence. audit runs both methods for each query and checks that their positions agree. Its two totals describe alternative paths, each including preparation once. They are not the total work of running the audit itself. No sorting is performed.

from dataclasses import dataclass


@dataclass(frozen=True, init=False)
class SortedIndex:
    values: tuple
    validation_comparisons: int

    def __init__(self, values):
        if type(values) not in (list, tuple):
            raise ValueError('values must be a list or tuple')
        if any(type(value) is not int for value in values):
            raise ValueError('values must contain integers, not Booleans')
        snapshot = tuple(values)
        checks = 0
        for i in range(1, len(snapshot)):
            checks += 1
            if snapshot[i] < snapshot[i - 1]:
                raise ValueError('values must already be sorted')
        object.__setattr__(self, 'values', snapshot)
        object.__setattr__(self, 'validation_comparisons', checks)

    def search(self, target, method='binary'):
        if type(target) is not int:
            raise ValueError('target must be an integer, not a Boolean')
        if type(method) is not str or method not in ('linear', 'binary'):
            raise ValueError('method must be linear or binary')
        comparisons = 0
        if method == 'linear':
            for i, value in enumerate(self.values):
                comparisons += 1
                if not value < target:
                    return i, comparisons
            return len(self.values), comparisons
        lo, hi = 0, len(self.values)
        while lo < hi:
            mid = (lo + hi) // 2
            comparisons += 1
            if self.values[mid] < target:
                lo = mid + 1
            else:
                hi = mid
        return lo, comparisons


def audit(values, queries):
    if type(queries) not in (list, tuple) or any(type(q) is not int for q in queries):
        raise ValueError('queries must be a list or tuple of integers')
    index = SortedIndex(values)
    rows = []
    for query in queries:
        left, linear = index.search(query, 'linear')
        right, binary = index.search(query, 'binary')
        if left != right:
            raise RuntimeError('search results disagree')
        rows.append((query, left, linear, binary))
    setup = index.validation_comparisons
    return {'n': len(index.values), 'validation_comparisons': setup,
            'rows': tuple(rows), 'binary_worst_bound': len(index.values).bit_length(),
            'linear_total': setup + sum(row[2] for row in rows),
            'binary_total': setup + sum(row[3] for row in rows)}


if __name__ == '__main__':
    report = audit([-3, -1, -1, 2, 5, 8, 8, 13], [-4, -1, 0, 8, 20])
    print('validation comparisons', report['validation_comparisons'])
    for row in report['rows']:
        print('target, position, linear, binary', row)
    print('separate totals', report['linear_total'], report['binary_total'])
    print('binary worst bound', report['binary_worst_bound'])
    print('empty', SortedIndex([]).search(7))

The output is:

validation comparisons 7
target, position, linear, binary (-4, 0, 1, 4)
target, position, linear, binary (-1, 1, 2, 4)
target, position, linear, binary (0, 3, 4, 3)
target, position, linear, binary (8, 5, 6, 3)
target, position, linear, binary (20, 8, 8, 3)
separate totals 28 24
binary worst bound 4
empty (0, 0)

The position for −1 is 1, even though −1 occurs twice. For 8 it is 5. A target of 20 returns 8: attempting to use that result as values[8] would be an error. Binary search loses to the scan on the first two queries and wins on the remaining three. Across this particular workload the search counts are 17 and 21; adding seven preparation comparisons gives the printed totals 24 and 28.

Let q be the number of queries. Under the stated constant-cost primitive model, successful index construction takes Theta(1+n) time, including type validation and the possible tuple copy. A prepared index answering q binary queries has:

Θ ⁣(1+n+q(1+log⁡2(n+1))) total time,O(1+n) index space,O(1) auxiliary space per search.\Theta\!\left(1+n+q\bigl(1+\log_2(n+1)\bigr)\right)\text{ total time},\qquad O(1+n)\text{ index space},\qquad O(1)\text{ auxiliary space per search}.

A stored tuple may be reused rather than copied; the space bound is an upper bound across both accepted input types. Returning a single position and count does not store the search path. Storing q results adds O(q) space. audit, which deliberately runs the scan as well, has worst-case time Theta(1+n+q(n+1)) and space O(1+n+q). An empty query list still constructs and validates the index. These formulas include constant work when n or q is zero.

If the input is unsorted, some other stage must sort it or use a different method. An O(n log n) comparison sort would add its own preparation cost. For one query, checking all input can dominate either search. For repeated queries on a stable validated snapshot, it is paid once.

Count what the machine actually has to do

The program accepts arbitrarily large Python integers. Its comparison counter stays valid, but a comparison of two large values need not cost one machine operation. If stored values and targets occupy at most b bits, a safe worst-case allowance per integer comparison is O(1+b); index arithmetic also depends on the number of bits in n unless covered by the word-RAM assumption. Report both element count and representation size when large integers matter. A loop that runs T times is linear in the numeric value T, but can be exponential in the length of T’s binary encoding.

Halving a copied slice does not make copying free. Replacing interval indices with slices of lengths about n/2, n/4 and so on introduces O(n) total copying, even though the comparison count remains logarithmic. Keeping all recursive slices alive can also use O(n) auxiliary space. The present implementation uses two indices and creates no such slices.

Locating an insertion position is not performing an insertion. A list may have to shift a linear number of references after a logarithmic search; the bisect performance notes call out that distinction. Similarly, computing all pairwise distances among n objects already produces n(n−1)/2 values. A faster inner lookup does not remove the quadratic output requirement when every value is requested.

Comparison counts do not capture cache behavior, interpreter overhead, vector instructions or I/O. Time a representative complete workload when choosing an implementation, and report preparation separately where reuse is real. Treat timing as evidence about those inputs and that environment. Use a proof to establish an asymptotic claim and profiling to find where an actual program spends its time.

Change the question before changing the bound

  1. There are 1,024 sorted entries. How many value comparisons can one binary search require? What if every query first validates the full sequence?

Answer: At most 11 search comparisons. Validation adds 1,023 adjacent comparisons plus type checking and other linear work. With validation repeated, each complete request has Theta(n) time under the stated model, despite its logarithmic search.

  1. The input is [2,2,2] and the target is 2. What answer is required? Is returning the first equal midpoint correct?

Answer: The boundary is 0. This program compares indices 1 and 0 and returns (0,2). Returning midpoint 1 after finding equality would satisfy an “any matching position” contract, but fails the lower-bound contract. Different outputs define different problems.

  1. For eight distinct entries and uniformly likely insertion ranks, derive the two mean comparison counts. Does the result establish average behavior for production queries?

Answer: Binary search gives (2×4+7×3)/9 = 29/9. The scan gives (1+2+3+4+5+6+7+8+8)/9 = 44/9. These expectations use the stated rank distribution. A workload concentrated before the first element makes the scan use one comparison each time, so the ranking can change.

  1. Someone says, “Amortized constant-time append means every append is fast, and a one-line loop over range(T) is polynomial in its input size.” Identify both missing conditions.

Answer: Amortized cost bounds the sequence total; an individual resize can be linear in the current number of elements. Input size must describe the encoding: a positive integer with b bits can be as large as 2 to the power b minus one. T iterations can therefore be exponential in b, even though each iteration’s body is short.

From a language statement to a mathematical model

The MIT computation-model lecture connects algorithms to allowed operations and explains why slicing, concatenation and large integers need their own costs. Its lower-bound lecture asks what any comparison procedure must learn. The resizing lecture shifts attention from one operation to a whole sequence. Together they distinguish a bound for an implementation, a lower bound for a computational model and an amortized guarantee.

The Python bisect reference supplies the concrete boundary semantics and separates search from insertion. Continue with data structures to see how representation changes available operations, and recursion and dynamic programming to analyze repeated subproblems. In an AI system, the same accounting applies to examples, features, candidate models and retrieved results: name each dimension before combining their costs.

Make a prediction, then check

A wrapper scans all n values to validate sorting before every logarithmic-time search. What is the complete request cost under constant-cost primitives?

Choose one answer

Learning objectives

  • State a search contract and prove its loop invariant and termination.
  • Distinguish comparison counts from preparation and full execution costs.
  • Separate worst-case, distributional average, amortized and bit-cost statements.

Prerequisites & connections

Explore related knowledge →

References

  1. 6.006 Lecture 2: Models of Computation
    Erik Demaine; Srini Devadas; MIT 6.006 course staff · 2011
  2. 6.006 Lecture 7: Linear-Time Sorting
    Erik Demaine; Srini Devadas; MIT 6.006 course staff · 2011
  3. 6.006 Lecture 9: Hashing II
    Erik Demaine; Srini Devadas; MIT 6.006 course staff · 2011
  4. bisect — Array Bisection Algorithm — Python 3.12
    Python Software Foundation and Python contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Six tests passed under CPython 3.12.12 and 3.12.4. Six datasets and 36 queries were checked against the defining rank set and partition postcondition, including duplicates, emptiness and 4097-bit signed magnitudes. Counters and wrapper totals were checked separately.
  • An independent dynamic program minimizes external path length over every full ordered binary-tree split up to 33 leaves. Eight index sizes and 78 insertion ranks attain those minima; worst depths attain the information bound. Exact means 29/9 and 44/9, snapshot mutation, empty batches, invalid types, duplicate-equality counterexamples and the 1024-entry bound were checked.
  • Identical bilingual original Python and nine stdout lines; four displays, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed, with matching math annotations. Humanizer reread; AI author checks only, written pending independent review. Draft files only.
  • Ran six author tests under Python 3.12.4. An independent tagged-event merge sorts query markers before equal-valued data records, deriving boundary ranks without either search or the author’s rank-set enumeration. It checks 42 insertion-gap queries over six sizes plus twelve duplicate/boundary queries.
  • For sizes 0,1,3,5,10,17, closed balanced-leaf/Kraft formulas check the entire depth histogram and aggregate comparison count: with L=n+1 leaves and h=ceil(log2 L), the shallow and deep leaf counts are 2^h−L and 2L−2^h. This differs from the author’s all-split external-path dynamic program. Separately, a deliberate reflection-based read proxy counts 38 successful stored-value accesses across ten searches and matches their declared comparisons; it is reviewer instrumentation beyond the normal frozen contract.
  • Read both full articles and verified half-open invariants, strict interval decrease, duplicates/empty semantics, exact worst recurrence, Boolean comparison-model lower bound, logarithmic best growth for this non-early-exit variant, uniform-rank mean assumptions, conceptual doubling amortization and preparation reuse. Space/time accounting includes snapshots, query output, the deliberately linear audit path and arbitrary-integer bit-cost qualifications. No revision was required.
  • Strict MDX/KaTeX and actual React HTML pass with four displays, six anchors and four answers per language. Four math annotations match; author tests confirm the identical program and nine stdout lines. Five final SHA values match the frozen manifest and source IDs/URLs are copied exactly from metadata. No author or repository files were edited.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • 6.006 Lecture 2: Models of Computation · Actually opened the eight-page official PDF; read printed pages 1–4 on abstract algorithms, allowed operations, word RAM, list indexing/copying/slicing and large integers. Historical timings on page 7 are not reused as current Python performance. Course directory identifies Fall 2011 and instructors. Text read; no scan-image inspection claimed.
  • 6.006 Lecture 7: Linear-Time Sorting · Actually read printed pages 1–3 of the five-page official PDF: comparison-only inputs, decision-tree paths and leaves, logarithmic search and n log n sorting lower bounds. The article gives its own n+1 boundary-outcome proof and exact halving recurrence.
  • 6.006 Lecture 9: Hashing II · Actually read printed pages 1–3 of the six-page official PDF, especially page 2 geometric resizing and amortization, page 3 resizable arrays. Expected hashing costs are not presented as worst-case deterministic guarantees; the conceptual doubling policy is not asserted to be CPython allocation policy.
  • bisect — Array Bisection Algorithm — Python 3.12 · Actually read the versioned page, displayed 3.12.13: bisect_left lines 8–15, insort lines 29–37, performance notes 52–59 and lookup boundary examples 65–100. Program is original and counts its own comparisons; bisect was not used as the primary test oracle.
  • 6.006 Lecture 2: Models of Computation · Actually opened the eight-page official MIT 6.006 Fall 2011 Lecture 2 PDF. Read printed pages 1–4 for operation/cost models, word RAM, indexed access, list copying/slicing and representation-dependent large-number arithmetic. Historical Python 2/Pentium timings were not treated as current benchmarks. Text read only; no diagram/scan visual audit or source-code copy.
  • 6.006 Lecture 7: Linear-Time Sorting · Actually read printed pages 1–3 of the five-page official MIT Lecture 7 PDF: comparison-model restriction, decision-tree leaves/paths and search/sort lower bounds. The article’s exact n+1 lower-bound-position outcomes and halving recurrence are its own explicitly scoped derivation, rather than an unqualified bound for all machines.
  • 6.006 Lecture 9: Hashing II · Actually read printed pages 1–3 of the six-page official MIT Lecture 9 PDF, particularly page 2 geometric resizing and whole-sequence amortization and page 3 resizable arrays. The draft correctly separates average-under-a-law from amortized cost and does not assert that the illustrative doubling policy is CPython’s actual policy.
  • bisect — Array Bisection Algorithm — Python 3.12 · Actually read Python /3.12 bisect reference rendered 3.12.13: lines 8–15 lower-bound partition and strict comparison, 29–37 insertion after search, and performance notes 52–59. No bisect execution was used for the independent oracle.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.