---
title: "The Cost of an Algorithm"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 17
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 17 — The Cost of an Algorithm

Two programs look for the names that appear twice in a list. They give the same answer. On a hundred names both answer at once; on a million names, one answers in well under a second and the other takes hours. Nothing in the answers tells them apart. What tells them apart is how much work each does, and how that work grows with the size of the list.

The previous chapter proved that a loop stops and gives the right answer. This one counts how many steps it takes before it stops: exactly, by counting operations in the code, and then roughly, by timing it. The two agree in a way that lets one predict, from a small run, how long a large one will take.

**You already know.**

Linear search, binary search, selection sort and insertion sort, with their invariants and variants, are in chapter [16](https://one-course.com/books/computer-science/2/en/chapter/16-proving-algorithms-correct#ch-g11-proving-algorithms-correct). Counting the comparisons a search or a sort makes, on small lists and by hand, was done in Book 1, grade 8.

## 17.1 Counting elementary operations

**Definition 17.1 (Elementary operation, input size).**

An *elementary operation* is an operation whose time does not depend on the size of the data: comparing two numbers, adding them, reading or writing one element of a list. The *input size* is a number that measures the data, usually written $n$: the length of a list, the number of names.

**Definition 17.2 (Cost).**

The *cost* of an algorithm on an input is the number of [elementary operations](#def-g11-cost-of-an-algorithm-elementary) it performs. One usually counts a single kind of operation that the others follow, such as the comparisons between elements in a search or a sort.

The simplest way to count is to let the program count: a variable that grows by one at each comparison.

```python
"""Linear search, counting its comparisons."""


def search(t, x):
    comparisons = 0
    for i in range(len(t)):
        comparisons += 1
        if t[i] == x:
            return i, comparisons
    return None, comparisons


if __name__ == "__main__":
    for n in [10, 100, 1000]:
        t = [f"name{k}" for k in range(n)]
        _, best = search(t, "name0")
        _, worst = search(t, "nobody")
        print(f"n = {n:4}: best case {best:4} comparison(s), worst case {worst:4}")
```

***Listing 17.1.** Linear search, counting its comparisons. code/grade-11/06-cost-of-an-algorithm/listings/count_linear.py*

```
$ python count_linear.py
n =   10: best case    1 comparison(s), worst case   10
n =  100: best case    1 comparison(s), worst case  100
n = 1000: best case    1 comparison(s), worst case 1000
```

***Output 17.1.** The first name [costs](#def-g11-cost-of-an-algorithm-cost) one comparison; a name that is absent [costs](#def-g11-cost-of-an-algorithm-cost) $n$.*

## 17.2 Best and worst case

**Definition 17.3 (Best case, worst case).**

For a given [input size](#def-g11-cost-of-an-algorithm-elementary) $n$, the *best case* of an algorithm is an input of size $n$ on which its [cost](#def-g11-cost-of-an-algorithm-cost) is the smallest, and the *worst case* one on which it is the largest. The [cost](#def-g11-cost-of-an-algorithm-cost) in the worst case is a promise: no input of that size [costs](#def-g11-cost-of-an-algorithm-cost) more.

Insertion sort shows how far apart the two may be. On a sorted list, each new element is compared once with the one before it and stays put. On a list in reverse order, each new element is compared with every element before it and travels to the front.

```python
"""Insertion sort, counting the comparisons between elements."""
import random


def insertion_sort(t):
    comparisons = 0
    for i in range(1, len(t)):
        x, j = t[i], i
        while j > 0:
            comparisons += 1
            if t[j - 1] <= x:
                break
            t[j] = t[j - 1]
            j -= 1
        t[j] = x
    return comparisons


if __name__ == "__main__":
    rng = random.Random(6)
    print("    n   sorted  shuffled  reversed   n(n-1)/2")
    for n in [10, 100, 1000]:
        shuffled = rng.sample(range(n), n)
        counts = [insertion_sort(t) for t in
                  (list(range(n)), shuffled, list(range(n, 0, -1)))]
        print(f"{n:5} {counts[0]:8} {counts[1]:9} {counts[2]:9} {n * (n - 1) // 2:10}")
```

***Listing 17.2.** Insertion sort, counting the comparisons between elements. code/grade-11/06-cost-of-an-algorithm/listings/count_insertion.py*

```
$ python count_insertion.py
    n   sorted  shuffled  reversed   n(n-1)/2
   10        9        31        45         45
  100       99      2798      4950       4950
 1000      999    251757    499500     499500
```

***Output 17.2.** A sorted list [costs](#def-g11-cost-of-an-algorithm-cost) $n - 1$ comparisons, a reversed one $n(n-1)/2$, and a shuffled one about half of that.*

![Insertion sort on six elements. Sorted: every new element is checked once against its left neighbour. Reversed: the last one, 1, is compared with all five before it on its way to the front.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-cost-of-an-algorithm/fig-e664c2795aeb.svg)

*Insertion sort on six elements. Sorted: every new element is checked once against its left neighbour. Reversed: the last one, $1$, is compared with all five before it on its way to the front.*

## 17.3 Constant, linear and quadratic cost

The exact count depends on details: counting assignments too, or starting the loop at $0$ or $1$, changes it a little. What does not change is how it grows with $n$.

**Definition 17.4 (Constant, linear, quadratic cost).**

A [cost](#def-g11-cost-of-an-algorithm-cost) is *constant* if it does not grow with $n$; *linear* if it is about proportional to $n$, so that doubling $n$ about doubles it; *quadratic* if it is about proportional to $n^2$, so that doubling $n$ about multiplies it by $4$.

Linear search [costs](#def-g11-cost-of-an-algorithm-cost) $n$ in its [worst case](#def-g11-cost-of-an-algorithm-cases): linear. Insertion sort [costs](#def-g11-cost-of-an-algorithm-cost) $n(n-1)/2 = (n^2 - n)/2$: for large $n$ the term $n^2/2$ is almost all of it, and the [cost](#def-g11-cost-of-an-algorithm-cost) is quadratic.

```python
"""What happens to each count when n doubles."""
from count_insertion import insertion_sort
from count_linear import search

previous = None
for n in [1000, 2000, 4000]:
    linear = search(list(range(n)), -1)[1]             # worst case: absent
    quadratic = insertion_sort(list(range(n, 0, -1)))  # worst case: reversed
    line = f"n = {n:4}: linear search {linear:5}, insertion sort {quadratic:9}"
    if previous:
        line += f"   ratios {linear / previous[0]:.2f}"
        line += f" and {quadratic / previous[1]:.2f}"
    print(line)
    previous = (linear, quadratic)
```

***Listing 17.3.** The worst-case counts when $n$ doubles. code/grade-11/06-cost-of-an-algorithm/listings/doubling.py*

```
$ python doubling.py
n = 1000: linear search  1000, insertion sort    499500
n = 2000: linear search  2000, insertion sort   1999000   ratios 2.00 and 4.00
n = 4000: linear search  4000, insertion sort   7998000   ratios 2.00 and 4.00
```

***Output 17.3.** Doubling $n$ doubles the linear count and multiplies the quadratic one by $4$.*

![Worst-case counts, from figures/counts.py. At n = 100, 100 comparisons against 4950; the straight line is not zero, it only looks flat beside the parabola.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-cost-of-an-algorithm/fig-474ab6529746.svg)

*Worst-case counts, from `figures/counts.py`. At $n = 100$, $100$ comparisons against $4950$; the straight line is not zero, it only looks flat beside the parabola.*

## 17.4 The cost of halving

Binary search does not look at the elements one by one: it halves the window each time. Its [cost](#def-g11-cost-of-an-algorithm-cost) is the [number of halvings](#def-g11-cost-of-an-algorithm-halvings).

**Definition 17.5 (Number of halvings).**

For a whole number $n \ge 1$, the *number of halvings* $h(n)$ is the number of times $n$ can be halved, rounding down, before it reaches $1$. It is the whole number $h$ such that $2^h \le n < 2^{h + 1}$.

```python
def h(n):
    """The number of times n can be halved (rounding down) before it reaches 1."""
    count = 0
    while n > 1:
        n = n // 2
        count += 1
    return count


print("         n   h(n)   2^h(n) <= n < 2^(h(n)+1)")
for n in [1, 2, 3, 7, 8, 1000, 10**6, 10**9]:
    k = h(n)
    assert 2**k <= n < 2**(k + 1)
    print(f"{n:10} {k:6}   {2**k:>10} <= n < {2**(k + 1)}")
```

***Listing 17.4.** $h(n)$, counted, and checked against the powers of $2$. code/grade-11/06-cost-of-an-algorithm/listings/halvings.py*

```
$ python halvings.py
         n   h(n)   2^h(n) <= n < 2^(h(n)+1)
         1      0            1 <= n < 2
         2      1            2 <= n < 4
         3      1            2 <= n < 4
         7      2            4 <= n < 8
         8      3            8 <= n < 16
      1000      9          512 <= n < 1024
   1000000     19       524288 <= n < 1048576
1000000000     29    536870912 <= n < 1073741824
```

***Output 17.4.** A thousand is halved $9$ times, a million $19$, a billion $29$: multiplying $n$ by a thousand adds about $10$.*

![Halving 1000, rounding down: after 9 halvings only 1 is left, so h(1000) = 9, and indeed 29 = 512 1000 < 1024.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-cost-of-an-algorithm/fig-94b25b5ef0f3.svg)

*Halving $1000$, rounding down: after $9$ halvings only $1$ is left, so $h(1000) = 9$, and indeed $2^9 = 512 \le 1000 < 1024$.*

The binary search of the previous chapter looks at one element, `t[mid]`, per turn, comparing it with `x` at most twice. Its window starts with $n$ elements, and each turn leaves at most half of it, rounded down. In the [worst case](#def-g11-cost-of-an-algorithm-cases) it makes $h(n) + 1$ turns: $20$ for a million names, against a million comparisons for linear search. Its [cost](#def-g11-cost-of-an-algorithm-cost) grows by one turn when $n$ doubles.

## 17.5 Measured running times

Counts predict running times, up to a factor that depends on the machine. `time.perf_counter()` reads a clock meant for measuring short times; the difference between two readings is the time spent between them. One run is never enough: the machine does other things at the same time, so each measurement is repeated and the median kept, the middle value, which an occasional slow run does not move.

```python
"""Running times of insertion sort when n doubles: the median of five runs."""
import random
import statistics
import time

from count_insertion import insertion_sort


def median_time(n, rng, runs=5):
    times = []
    for _ in range(runs):
        t = rng.sample(range(n), n)       # a new shuffled list for each run
        start = time.perf_counter()
        insertion_sort(t)
        times.append(time.perf_counter() - start)
    return statistics.median(times)


rng = random.Random(1)
previous = None
for n in [1000, 2000, 4000]:
    seconds = median_time(n, rng)
    ratio = f"   x {seconds / previous:.1f}" if previous else ""
    print(f"n = {n}: {seconds * 1000:7.1f} ms{ratio}")
    previous = seconds
```

***Listing 17.5.** Timing insertion sort as $n$ doubles. code/grade-11/06-cost-of-an-algorithm/listings/measure_sorts.py*

```
$ python measure_sorts.py
n = 1000:    11.3 ms
n = 2000:    45.3 ms   x 4.0
n = 4000:   189.4 ms   x 4.2
```

***Output 17.5.** Measured on the author’s laptop: each doubling multiplies the time by about $4$, as the quadratic count predicted.*

![Insertion sort on shuffled lists, median of five runs, measured on the author’s laptop (figures/measured_plot.py). The dashed lines mark n = 1000, 2000, 4000: each doubling, about four times the time.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-cost-of-an-algorithm/fig-ef7b0bdaf32a.svg)

*Insertion sort on shuffled lists, median of five runs, measured on the author’s laptop (`figures/measured_plot.py`). The dashed lines mark $n = 1000$, $2000$, $4000$: each doubling, about four times the time.*

The same machine, looking for a number in a million: a scan of the list against a binary search and against a set, which finds an element by computing where it is stored rather than by comparing.

```python
"""One lookup in a million numbers: a list, binary search, a set."""
import bisect
import statistics
import time

N = 10**6
numbers = list(range(0, 2 * N, 2))       # sorted, even numbers only
as_set = set(numbers)
targets = [N + 1, 2 * N - 2]             # absent (odd), and the very last one


def per_lookup(found, runs=5, repeat=20):
    times = []
    for _ in range(runs):
        start = time.perf_counter()
        for _ in range(repeat):
            for x in targets:
                found(x)
        times.append((time.perf_counter() - start) / (repeat * len(targets)))
    return statistics.median(times)


def in_sorted(x):
    i = bisect.bisect_left(numbers, x)
    return i < len(numbers) and numbers[i] == x


for name, found in [("x in list", lambda x: x in numbers),
                    ("binary search", in_sorted),
                    ("x in set", lambda x: x in as_set)]:
    print(f"{name:14} {per_lookup(found) * 1e6:10.3f} microseconds per lookup")
```

***Listing 17.6.** One lookup in a million numbers, three ways. code/grade-11/06-cost-of-an-algorithm/listings/measure_search.py*

```
$ python measure_search.py
x in list        5855.435 microseconds per lookup
binary search       0.141 microseconds per lookup
x in set            0.033 microseconds per lookup
```

***Output 17.6.** Measured on the author’s laptop. The scan is tens of thousands of times slower than binary search on a million elements.*

**Remark 17.6.**

A timing measures everything between the two clock readings. A `print` inside the timed part, or building the list there, is measured too. Timings also vary from run to run and from machine to machine: this book’s timings are printed as measured once, on one laptop, and only their ratios are meant to carry over.

## 17.6 Exercises

**Exercise 17.1 ★.**

How many comparisons does linear search make, in its [worst case](#def-g11-cost-of-an-algorithm-cases), on a list of $500$ names? When is that case?

**Solution of Exercise 17.1.**

$500$, when the name is absent, or is the last one: every element is compared.

**Exercise 17.2 ★.**

Compute $h(1000)$ by halving by hand, and check it with powers of $2$.

**Solution of Exercise 17.2.**

$1000$, $500$, $250$, $125$, $62$, $31$, $15$, $7$, $3$, $1$: nine halvings, $h(1000) = 9$. Check: $2^9 = 512 \le 1000 < 1024 = 2^{10}$.

**Exercise 17.3 ★.**

What does `count_insertion.py` print for the sorted and the reversed lists if $n = 20$?

**Solution of Exercise 17.3.**

$19$ for the sorted list ($n - 1$) and $190$ for the reversed one ($20 \times 19 / 2$); the last column prints $190$ too. The shuffled column depends on the shuffle.

**Exercise 17.4 ★.**

How many times does the body run in `for i in range(n)`, then inside it `for j in range(i)`? Give the count for $n = 10$ and in general.

**Solution of Exercise 17.4.**

For each `i`, the inner body runs `i` times: $0 + 1 + \dots + 9 = 45$ for $n = 10$, and $0 + 1 + \dots + (n - 1) = n(n - 1)/2$ in general, by the pairing of exercise [17.6](#exo-g11-cost-of-an-algorithm-6).

**Exercise 17.5 ★.**

Write `count_comparisons(sort, t)` that sorts a copy of `t` with a given sorting function, such as `sorted`, and returns how many comparisons it made. Hint: `functools.cmp_to_key` turns a comparison function into a key.

**Solution of Exercise 17.5.**

    `def count_comparisons(sort, t):`

        `count = 0`

        `def less(a, b):`

            `nonlocal count`

            `count += 1`

            `return -1 if a < b else (1 if b < a else 0)`

        `key = functools.cmp_to_key(less)`

        `sort([key(v) for v in t])`

        `return count`

Each comparison the sort makes between two keys calls `less` once. On a sorted list of $10$ elements, `sorted` makes $9$.

**Exercise 17.6 ★★.**

Selection sort compares, at turn $i$, the element in place $i$ and those after it. Show that it makes exactly $n(n-1)/2$ comparisons on every list, by writing the sum $(n-1) + (n-2) + \dots + 1$ twice, the second time backwards, and adding.

**Solution of Exercise 17.6.**

Turn $i$ compares place $i$ with the $n - 1 - i$ places after it, whatever the values: in all $S = (n - 1) + (n - 2) + \dots + 1$. Written backwards, $S = 1 + 2 + \dots + (n - 1)$. Adding the two lines term by term gives $n - 1$ sums, each equal to $n$: $2S = n(n - 1)$, so $S = n(n - 1)/2$.

**Exercise 17.7 ★★.**

A student times a sort with a `print` of the list after each turn, inside the timed part. Why is the measurement wrong, and what does it measure?

**Solution of Exercise 17.7.**

Printing a list writes every element as text and sends it to the screen, which takes far longer than a comparison. The timing then measures mostly the printing, which grows with the list printed at each turn, and depends on the terminal, not on the sort. Time the sort alone, and print afterwards.

**Exercise 17.8 ★★.**

A quadratic [cost](#def-g11-cost-of-an-algorithm-cost) takes $2$ seconds for $n = 10\,000$. About how long for $n = 30\,000$?

**Solution of Exercise 17.8.**

Tripling $n$ multiplies a quadratic [cost](#def-g11-cost-of-an-algorithm-cost) by $3^2 = 9$: about $18$ seconds.

**Exercise 17.9 ★★.**

Write `has_duplicate(t)` that compares every pair of elements once, and give its number of comparisons when there is no duplicate.

**Solution of Exercise 17.9.**

    `def has_duplicate(t):`

        `for i in range(len(t)):`

            `for j in range(i + 1, len(t)):`

                `if t[i] == t[j]:`

                    `return True`

        `return False`

Without a duplicate, every pair is compared once: $n(n - 1)/2$ comparisons.

**Exercise 17.10 ★★.**

Which list of length $n$ is the [worst case](#def-g11-cost-of-an-algorithm-cases) for the chapter’s `largest`, if one counts the assignments `best = t[i]`? How many are there then?

**Solution of Exercise 17.10.**

A list in increasing order, all different: every `t[i]` is larger than the best so far, so the assignment runs at each of the $n - 1$ turns.

**Exercise 17.11 ★★.**

Write `h(n)` by halving, and check on all $n$ from $1$ to $5000$ that $2^{h(n)} \le n < 2^{h(n) + 1}$.

**Solution of Exercise 17.11.**

    `def h(n):`

        `count = 0`

        `while n > 1:`

            `n //= 2`

            `count += 1`

        `return count`

The check is a loop over `range(1, 5001)` with `assert 2**k <= n < 2**(k + 1)`; the tests run it.

**Exercise 17.12 ★★★.**

Prove that the binary search of the previous chapter makes at most $h(n) + 1$ turns on a list of $n \ge 1$ elements.

**Solution of Exercise 17.12.**

Let $w = \mathit{hi} - \mathit{lo}$ be the window’s size, $n$ at the start. A turn that does not return leaves either $\mathit{mid} - \mathit{lo} = \lfloor w/2 \rfloor$ elements, or $\mathit{hi} - \mathit{mid} - 1$, which is $\lceil w/2 \rceil - 1 \le \lfloor w/2 \rfloor$: at most half of $w$, rounded down. So after $k$ turns the window has at most as many elements as $n$ halved $k$ times, rounding down each time. After $h(n)$ turns that is $1$, by the definition of $h(n)$; a window of $1$ element allows one more turn, after which it is empty and the loop stops. In all, at most $h(n) + 1$ turns, hence at most $h(n) + 1$ elements `t[mid]` looked at.

**Exercise 17.13 ★★★.**

Rank the [costs](#def-g11-cost-of-an-algorithm-cost) $1000$, $h(n)$, $100n$, $n \cdot h(n)$ and $n^2$ at $n = 10$, $1000$ and $10^6$. Which is smallest at $n = 10$? Is $n \cdot h(n)$ below $100n$ at $n = 10^6$? What does this say about comparing [costs](#def-g11-cost-of-an-algorithm-cost) only by their growth?

**Solution of Exercise 17.13.**

| [cost](#def-g11-cost-of-an-algorithm-cost) | $n = 10$ | $n = 1000$ | $n = 10^6$ |
| --- | --- | --- | --- |
| $1000$ | $1000$ | $1000$ | $1000$ |
| $h(n)$ | $3$ | $9$ | $19$ |
| $100n$ | $1000$ | $100\,000$ | $10^8$ |
| $n \cdot h(n)$ | $30$ | $9000$ | $1.9 \times 10^7$ |
| $n^2$ | $100$ | $10^6$ | $10^{12}$ |

At $n = 10$ the smallest is $h(n)$, then $n \cdot h(n)$, $n^2$, and $1000$ and $100n$ tie. At $10^6$, $n \cdot h(n)$ is still five times below $100n$, although it grows faster: it passes $100n$ only when $h(n)$ passes $100$, for $n$ beyond $2^{100}$, a size no list will ever have. How a [cost](#def-g11-cost-of-an-algorithm-cost) grows tells which wins for large enough $n$; the [constants](#def-g11-cost-of-an-algorithm-growth) tell what “large enough” means.

**Exercise 17.14 ★★★.**

Write a duplicate search that sorts the list and then compares neighbours. How many comparisons does the scan make?

**Solution of Exercise 17.14.**

    `def duplicates_by_sorting(t):`

        `s = sorted(t)`

        `return any(s[k] == s[k + 1] for k in range(len(s) - 1))`

The scan makes at most $n - 1$ comparisons, a linear [cost](#def-g11-cost-of-an-algorithm-cost); the sort is the larger part, as the weekend problem measures.

**Exercise 17.15 ★★★.**

From the three times of `measure_sorts.py`, predict the time of insertion sort for $n = 40\,000$. Running it would take a while: estimate how long, and say why the prediction might be off.

**Solution of Exercise 17.15.**

From $4000$ to $40\,000$ the size is multiplied by $10$, so a quadratic time by $100$: about $100$ times the time printed for $n = 4000$, a little under $20$ seconds on the author’s laptop. The prediction may be off: a list ten times larger no longer fits in the processor’s fastest memory, the machine may be busy, and the small terms of the [cost](#def-g11-cost-of-an-algorithm-cost), negligible at large $n$, were not negligible in the measurement at $4000$.

## 17.7 Problem: Two Ways to Find Duplicates

**Problem 17.1.**

Weekend problem — from which size sorting first pays

A list of $n$ numbers may hold a duplicate. Three functions answer: one compares every pair, one sorts the list with Python’s `sorted` and compares neighbours, one builds a set. The first two are counted with a value that counts each comparison made with it; the third compares nothing, it computes where each number goes.

```python
"""Three ways to find whether a list has a duplicate, counting comparisons."""


class Counted:
    """A value that counts every comparison made with < or ==."""
    count = 0

    def __init__(self, v):
        self.v = v

    def __lt__(self, other):
        Counted.count += 1
        return self.v < other.v

    def __eq__(self, other):
        Counted.count += 1
        return self.v == other.v


def by_pairs(t):                  # every pair once: i < j
    for i in range(len(t)):
        for j in range(i + 1, len(t)):
            if t[i] == t[j]:
                return True
    return False


def by_sorting(t):                # equal values end up side by side
    s = sorted(t)
    return any(s[k] == s[k + 1] for k in range(len(s) - 1))


def by_set(t):                    # no comparisons counted: hashing instead
    return len(set(t)) < len(t)
```

***Listing 17.7.** Three ways to find a duplicate, and a counted value. code/grade-11/06-cost-of-an-algorithm/listings/duplicates.py*

```python
"""The weekend problem, part I and II: comparisons when there is no duplicate."""
import random

from duplicates import Counted, by_pairs, by_sorting


def comparisons(find, values):
    Counted.count = 0
    assert not find([Counted(v) for v in values])
    return Counted.count


rng = random.Random(2026)
last_loss = 1                     # the last n where pairs did not lose
for n in range(2, 101):
    values = rng.sample(range(10 * n), n)       # n different values, shuffled
    pairs = comparisons(by_pairs, values)
    sorting = comparisons(by_sorting, values)
    if sorting >= pairs:
        last_loss = n
    if n in (2, 5, 10, 20, 50, 100):
        print(f"n = {n:3}: pairs {pairs:5}   sort then scan {sorting:4}")
print("sort then scan needs fewer comparisons from n =", last_loss + 1, "up to 100")
for n in (1000, 10**5):
    values = rng.sample(range(10 * n), n)
    print(f"n = {n}: pairs {n * (n - 1) // 2} (by the formula)   sort then scan",
          comparisons(by_sorting, values))
```

***Listing 17.8.** Counting the comparisons on lists without duplicates. code/grade-11/06-cost-of-an-algorithm/listings/dup_count.py*

```
$ python dup_count.py
n =   2: pairs     1   sort then scan    2
n =   5: pairs    10   sort then scan   11
n =  10: pairs    45   sort then scan   32
n =  20: pairs   190   sort then scan   80
n =  50: pairs  1225   sort then scan  268
n = 100: pairs  4950   sort then scan  631
sort then scan needs fewer comparisons from n = 7 up to 100
n = 1000: pairs 499500 (by the formula)   sort then scan 9636
n = 100000: pairs 4999950000 (by the formula)   sort then scan 1628843
```

***Output 17.7.** The counts, on shuffled lists of different numbers.*

```python
"""The weekend problem, part III and IV: running times, median of three runs."""
import random
import statistics
import time

from duplicates import by_pairs, by_set, by_sorting


def seconds(find, values, runs=3):
    times = []
    for _ in range(runs):
        start = time.perf_counter()
        assert not find(values)
        times.append(time.perf_counter() - start)
    return statistics.median(times)


rng = random.Random(7)
pairs = {}
for n in (1000, 2000, 4000):
    values = rng.sample(range(10 * n), n)
    pairs[n] = seconds(by_pairs, values)
    print(f"n = {n:6}: pairs {pairs[n] * 1000:9.1f} ms")
values = rng.sample(range(10**6), 10**5)
sorting, hashing = seconds(by_sorting, values), seconds(by_set, values)
guess = pairs[4000] * (10**5 / 4000) ** 2           # a quadratic cost: x 625
print(f"n = 100000: sort then scan {sorting * 1000:.1f} ms,"
      f" set {hashing * 1000:.1f} ms")
print(f"pairs at n = 100000, from n = 4000 times 625: about {guess:.0f} s")
print(f"speed-up of sort then scan: about {guess / sorting:,.0f} times")
```

***Listing 17.9.** Timing the three, and predicting the quadratic one at $n = 100\,000$. code/grade-11/06-cost-of-an-algorithm/listings/dup_measure.py*

```
$ python dup_measure.py
n =   1000: pairs       8.0 ms
n =   2000: pairs      32.7 ms
n =   4000: pairs     129.2 ms
n = 100000: sort then scan 20.2 ms, set 5.1 ms
pairs at n = 100000, from n = 4000 times 625: about 81 s
speed-up of sort then scan: about 4,000 times
```

***Output 17.8.** Measured on the author’s laptop.*

**Part I — Every pair.**

1. Why is a list without duplicate the [worst case](#def-g11-cost-of-an-algorithm-cases) of `by_pairs` ?
2. Count its comparisons on such a list of $n$ elements, and check the line $n = 100$ .
3. Is its [cost](#def-g11-cost-of-an-algorithm-cost) [constant](#def-g11-cost-of-an-algorithm-growth) , linear or quadratic?
4. What does `Counted` do, and why can it count the comparisons made inside `sorted` ?
5. Why is `by_pairs` not run at $n = 100\,000$ in `dup_count.py` ?

**Part II — Sort, then scan.**

6. Why do two equal values end up side by side once the list is sorted?
7. How many comparisons does the scan make, at most?
8. Subtract them from the printed counts at $n = 10$ and $n = 100$ : how many comparisons did the sort make?
9. From the output, from which $n$ does sorting win, on these lists? Why did it lose for small $n$ ?
10. At $n = 100\,000$ , how many times fewer comparisons than every pair?

**Part III — The measured times.**

11. Check that the times of `by_pairs` at $1000$ , $2000$ , $4000$ grow like a quadratic [cost](#def-g11-cost-of-an-algorithm-cost) .
12. Explain the factor $625$ in the prediction for $n = 100\,000$ .
13. Express the predicted time in minutes.
14. The set version compares nothing. Why can it still not take a [constant](#def-g11-cost-of-an-algorithm-growth) time?
15. Rank the three by measured time at $n = 100\,000$ .

**Part IV — The verdict.**

16. Check the printed speed-up from the two times it divides.
17. Why is the speed-up measured in time different from the ratio of comparisons of question 10?
18. For a list of a thousand numbers checked once, does the choice matter? For a million?
19. Why is the prediction for `by_pairs` at $100\,000$ reasonable but not exact?
20. State the result: the size from which sorting needs fewer comparisons, and the speed-up measured at $n = 100\,000$ .

**Solution of Problem 17.1.**

**1.** It can answer `False` only after checking every pair; with a duplicate it may stop at the first equal pair.

**2.** Each pair $i < j$ once: $n(n - 1)/2$. For $n = 100$, $4950$, as printed.

**3.** Quadratic.

**4.** It wraps a number and counts, in a variable shared by all its values, each call to `<` or `==`. `sorted` compares the elements with `<`, so each of its comparisons calls `Counted.__lt__` once and is counted.

**5.** Its count is known exactly, $4\,999\,950\,000$, by the formula; running five billion counted comparisons in Python would take hours.

**6.** If `s[i] == s[j]` with $i < j$, everything between them in the sorted list lies between the two equal values, so is equal to them; in particular `s[i + 1] == s[i]`.

**7.** $n - 1$, one per pair of neighbours, when there is no duplicate.

**8.** At $n = 10$: $32 - 9 = 23$ comparisons for the sort. At $n = 100$: $631 - 99 = 532$.

**9.** From $n = 7$, for every size up to $100$ on these lists. For small $n$, the sort’s own comparisons plus the $n - 1$ of the scan are more than all the pairs: at $n = 5$, $11$ against $10$.

**10.** $4\,999\,950\,000 / 1\,628\,843 \approx 3070$ times fewer.

**11.** $8.0$, $32.7$ and $129.2$ ms: each doubling multiplies the time by about $4$.

**12.** $100\,000 / 4000 = 25$, and a quadratic time grows like the square: $25^2 = 625$.

**13.** About $81$ s, a little under a minute and a half.

**14.** Building the set reads each of the $n$ numbers once: its [cost](#def-g11-cost-of-an-algorithm-cost) is linear, it grows with $n$.

**15.** The set, $5.1$ ms; sort then scan, $20.2$ ms; every pair, about $81$ s, predicted.

**16.** $81 / 0.0202 \approx 4000$, as printed.

**17.** A comparison [costs](#def-g11-cost-of-an-algorithm-cost) a different time in each: `sorted` compares numbers inside Python’s own fast machinery, while `by_pairs` runs two Python loops around each comparison; the sort also moves elements, which is counted in time but not in comparisons. Counts predict how a time grows, not the ratio between two programs.

**18.** For a thousand numbers checked once, $8$ ms against a fraction of a millisecond: it hardly matters. For a million, the pairs would take $250^2 = 62\,500$ times the time at $n = 4000$, more than two hours, against a fraction of a second.

**19.** The time also has smaller terms that the square neglects, and a large list behaves differently in the machine’s memory; the prediction extends a law measured from $1000$ to $4000$ far beyond where it was measured.

**20.** On these shuffled lists of different numbers, **sort then scan needs fewer comparisons than every pair from $n = 7$ on**; at $n = 100\,000$ it was measured **about $4000$ times faster** on the author’s laptop ($20.2$ ms against about $81$ s predicted for every pair), and a set was faster still.
