---
title: "Searching and Sorting"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 28
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/28-searching-and-sorting
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 28 — Searching and Sorting

To find the word *otter* in a paper [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary), nobody starts at the first page and reads every word. You open it near the middle, see that you are in the *m*s, and go on in the second half; a few openings later the word is in front of you. That works because the words are in alphabetical order. This chapter teaches a [computer](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer) both ways of searching, and two ways of putting a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) in order first.

**You already know.**

A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) keeps [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) in order, each at a position, its [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), from 0 ([Chapter 20](https://one-course.com/books/computer-science/1/en/chapter/20-lists#ch-g7-lists)); a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) takes [parameters](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-parameter) and returns a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) ([Chapter 19](https://one-course.com/books/computer-science/1/en/chapter/19-functions#ch-g7-functions)). The guessing game of [Chapter 18](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#ch-g6-while-loops) asks “higher or lower?” until the guess is right. $n$ [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) make $2^n$ patterns, and each extra [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) doubles their number ([Chapter 25](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#ch-g8-binary-and-hexadecimal)).

## 28.1 Searching item by item

**Definition 28.1 (Linear search).**

A *linear search* looks at the [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) one after the other, from the first, until it finds the one it looks for or reaches the end.

The [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) returns the position of the target, or $-1$ when it is not in the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), a position that cannot exist. It also counts its [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison), to measure its work.

```python
def linear_search(items, target):
    """The position of target in items, or -1; also the number of comparisons."""
    comparisons = 0
    for i in range(len(items)):
        comparisons = comparisons + 1
        if items[i] == target:
            return i, comparisons
    return -1, comparisons


if __name__ == "__main__":
    ages = [12, 9, 15, 11, 9, 14, 13, 10]
    for target in [12, 13, 7]:
        print(target, linear_search(ages, target))
```

***Listing 28.1.** [Linear search](#def-g8-searching-and-sorting-linear-search), counting its [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison). code/grade-8/04-searching-and-sorting/listings/linear_search.py*

```
$ python linear_search.py
12 (0, 1)
13 (6, 7)
7 (-1, 8)
```

***Output 28.1.** Position and [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison).*

The [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) returns two [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), written with a comma; Python prints them in brackets. Finding 12 takes one [comparison](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison), because it is first; 13 takes 7. Looking for 7, which is not there, takes 8: every [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is looked at. This is the *worst case*: for a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of a million [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), a million [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison).

![Linear search for 13: one cell after the other, from the left.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-searching-and-sorting/fig-28337c03e4a4.svg)

*[Linear search](#def-g8-searching-and-sorting-linear-search) for 13: one cell after the other, from the left.*

## 28.2 Searching a sorted list by halving

**Definition 28.2 (Sorted list).**

A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is *sorted* (in increasing order) when each [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is smaller than or equal to the next one.

**Definition 28.3 (Binary search).**

A *binary search* looks for an [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) in a [sorted list](#def-g8-searching-and-sorting-sorted) by comparing it with the middle [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), then going on in the half where it must be, and halving again until it is found or no [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is left.

This is the good strategy of the guessing game: guess 50 between 1 and 100; “higher” leaves 51 to 100, so guess 75; and so on. The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) keeps two positions, `low` and `high`: the target, if it is there, lies between them.

```python
def binary_search(items, target):
    """The position of target in the sorted list items, or -1; also the guesses."""
    low = 0
    high = len(items) - 1
    guesses = 0
    while low <= high:
        middle = (low + high) // 2
        guesses = guesses + 1
        if items[middle] == target:
            return middle, guesses
        elif items[middle] < target:
            low = middle + 1          # target is in the right half
        else:
            high = middle - 1         # target is in the left half
    return -1, guesses


if __name__ == "__main__":
    numbers = list(range(1, 101))
    for target in [50, 37, 100, 1]:
        print(target, binary_search(numbers, target))
```

***Listing 28.2.** [Binary search](#def-g8-searching-and-sorting-binary-search) between `low` and `high`. code/grade-8/04-searching-and-sorting/listings/binary_search.py*

```
$ python binary_search.py
50 (49, 1)
37 (36, 3)
100 (99, 7)
1 (0, 6)
```

***Output 28.2.** Never more than 7 guesses between 1 and 100.*

`//` divides and drops the remainder, so `middle` is always a whole position. The trace below follows the search for 77 in a [sorted](#def-g8-searching-and-sorting-sorted) row of 16 numbers:

```python
items = [2, 5, 8, 12, 16, 23, 38, 41, 47, 56, 61, 72, 77, 85, 90, 98]
target = 77
low = 0
high = len(items) - 1
found = False
while low <= high and not found:
    middle = (low + high) // 2
    print("low", low, "middle", middle, "high", high, "->", items[middle])
    if items[middle] == target:
        found = True
    elif items[middle] < target:
        low = middle + 1
    else:
        high = middle - 1
print("found:", found)
```

***Listing 28.3.** The search, with `low`, `middle` and `high` printed at each step. code/grade-8/04-searching-and-sorting/listings/binary_search_trace.py*

```
$ python binary_search_trace.py
low 0 middle 7 high 15 -> 41
low 8 middle 11 high 15 -> 72
low 12 middle 13 high 15 -> 85
low 12 middle 12 high 12 -> 77
found: True
```

***Output 28.3.** Four steps for 16 numbers.*

![Binary search for 77 among 16 sorted numbers: each bracket is the part still searched, from low to high, and the red dot the middle item compared. Four steps.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-searching-and-sorting/fig-4892d94128bd.svg)

*[Binary search](#def-g8-searching-and-sorting-binary-search) for 77 among 16 [sorted](#def-g8-searching-and-sorting-sorted) numbers: each bracket is the part still searched, from `low` to `high`, and the red dot the middle [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) compared. Four steps.*

How many guesses can [binary search](#def-g8-searching-and-sorting-binary-search) need? Each guess removes the middle [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) and at least half of the others. One guess is enough for 1 [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), two for 3, three for 7: $k$ guesses are enough for $2^k - 1$ [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). With 100 [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), 6 guesses cover only $2^6 - 1 = 63$, but 7 cover $2^7 - 1 = 127$: the doublings of [Chapter 25](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#ch-g8-binary-and-hexadecimal), read backwards.

The halving only makes sense if the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is [sorted](#def-g8-searching-and-sorting-sorted). On an unsorted [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) still runs, and still answers, but the answer can be wrong:

```python
from binary_search import binary_search
from linear_search import linear_search

ages = [12, 9, 15, 11, 9, 14, 13, 10]       # not sorted
print("binary:", binary_search(ages, 15))
print("linear:", linear_search(ages, 15))
```

***Listing 28.4.** [Binary search](#def-g8-searching-and-sorting-binary-search) on a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) that is not [sorted](#def-g8-searching-and-sorting-sorted). code/grade-8/04-searching-and-sorting/listings/unsorted_binary.py*

```
$ python unsorted_binary.py
binary: (-1, 4)
linear: (2, 3)
```

***Output 28.4.** 15 is at position 2, but [binary search](#def-g8-searching-and-sorting-binary-search) says it is not there.*

The first middle [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is 11, smaller than 15, so the search goes right, where 15 is not. No [error message](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-error) warns about it: making sure the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is [sorted](#def-g8-searching-and-sorting-sorted) is the programmer’s job.

## 28.3 Selection sort

**Definition 28.4 (Selection sort).**

*Selection sort* finds the smallest [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) and swaps it to the front, then does the same on the rest of the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), one position further each time.

```python
def selection_sort(items):
    """Sort items in place, smallest first; return the number of comparisons."""
    comparisons = 0
    for start in range(len(items) - 1):
        smallest = start
        for i in range(start + 1, len(items)):
            comparisons = comparisons + 1
            if items[i] < items[smallest]:
                smallest = i
        items[start], items[smallest] = items[smallest], items[start]   # swap the two
    return comparisons


if __name__ == "__main__":
    cards = [7, 3, 9, 1, 8, 4]
    print(selection_sort(cards), "comparisons:", cards)
```

***Listing 28.5.** [Selection sort](#def-g8-searching-and-sorting-selection-sort), counting its [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison). code/grade-8/04-searching-and-sorting/listings/selection_sort.py*

```
$ python selection_sort.py
15 comparisons: [1, 3, 4, 7, 8, 9]
```

***Output 28.5.** 6 cards, 15 [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison).*

`a, b = b, a` swaps two [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) in one line. The [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) changes the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) it receives, *in place*, as `append` does ([Chapter 20](https://one-course.com/books/computer-science/1/en/chapter/20-lists#ch-g7-lists)), and returns its number of [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison).

![Selection sort on 6 cards: after each pass, one more card (green) is in its final place.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-searching-and-sorting/fig-963fac803a88.svg)

*[Selection sort](#def-g8-searching-and-sorting-selection-sort) on 6 cards: after each pass, one more card (green) is in its final place.*

The first pass compares 5 pairs, the next 4, then 3, 2 and 1: $5+4+3+2+1 = 15$ [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison), whatever the order of the cards.

## 28.4 Insertion sort

**Definition 28.5 (Insertion sort).**

*Insertion sort* takes the [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) one after the other and slides each one back, among those already [sorted](#def-g8-searching-and-sorting-sorted) before it, until it reaches its place.

It is how many card players sort a hand: pick up the cards one at a time, and put each one where it belongs among those already held.

```python
def insertion_sort(items):
    """Sort items in place, smallest first; return the number of comparisons."""
    comparisons = 0
    for i in range(1, len(items)):
        j = i
        moving = True
        while moving and j > 0:
            comparisons = comparisons + 1
            if items[j - 1] > items[j]:
                items[j - 1], items[j] = items[j], items[j - 1]   # swap the two
                j = j - 1
            else:
                moving = False         # in its place among the sorted ones
    return comparisons


if __name__ == "__main__":
    cards = [7, 3, 9, 1, 8, 4]
    print(insertion_sort(cards), "comparisons:", cards)
```

***Listing 28.6.** [Insertion sort](#def-g8-searching-and-sorting-insertion-sort), counting its [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison). code/grade-8/04-searching-and-sorting/listings/insertion_sort.py*

```
$ python insertion_sort.py
11 comparisons: [1, 3, 4, 7, 8, 9]
```

***Output 28.6.** The same 6 cards, 11 [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison).*

![Insertion sort on the same 6 cards: the yellow part is sorted, and grows by one card each pass.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-searching-and-sorting/fig-85db6b2bf33f.svg)

*[Insertion sort](#def-g8-searching-and-sorting-insertion-sort) on the same 6 cards: the yellow part is [sorted](#def-g8-searching-and-sorting-sorted), and grows by one card each pass.*

## 28.5 Counting comparisons to compare two methods

Both sorts give the same [sorted list](#def-g8-searching-and-sorting-sorted). Which one works less? The [counters](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#def-g6-while-loops-counter) answer, on [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of 10, 100 and 1,000 numbers, already [sorted](#def-g8-searching-and-sorting-sorted), in reverse, or mixed. The mixed order is fixed in the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program), so the counts are the same at every run.

```python
from insertion_sort import insertion_sort
from selection_sort import selection_sort


def mixed(n):
    """The numbers 0 to n - 1 in a fixed mixed order: the remainders of 37 x i by n."""
    items = []
    for i in range(n):
        items.append((37 * i) % n)
    return items


if __name__ == "__main__":
    print("n      order      selection  insertion")
    for n in [10, 100, 1000]:
        for name in ["sorted", "reversed", "mixed"]:
            if name == "sorted":
                items = list(range(n))
            elif name == "reversed":
                items = list(range(n, 0, -1))
            else:
                items = mixed(n)
            by_selection = selection_sort(list(items))
            by_insertion = insertion_sort(list(items))
            print(f"{n:<6} {name:<10} {by_selection:>9} {by_insertion:>10}")
```

***Listing 28.7.** The two sorts on the same [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). code/grade-8/04-searching-and-sorting/listings/count_comparisons.py*

```
$ python count_comparisons.py
n      order      selection  insertion
10     sorted            45          9
10     reversed          45         45
10     mixed             45         27
100    sorted          4950         99
100    reversed        4950       4950
100    mixed           4950       2547
1000   sorted        499500        999
1000   reversed      499500     499500
1000   mixed         499500     252747
```

***Output 28.7.** [Comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) of the two sorts.*

[Selection sort](#def-g8-searching-and-sorting-selection-sort) always makes the same number of [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) for $n$ [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list): $(n-1) + (n-2) + \dots + 1$, which is $n(n-1)/2$, so 45 for 10 [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) and 499,500 for 1,000. [Insertion sort](#def-g8-searching-and-sorting-insertion-sort) depends on the order. On a [sorted list](#def-g8-searching-and-sorting-sorted), each [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is compared once with the one before it and stays: $n - 1$ [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison). On a reversed [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), each [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) slides all the way to the front, and it makes as many [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) as [selection sort](#def-g8-searching-and-sorting-selection-sort). On the mixed [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) it lies in between, about half of the most.

![Comparisons against the number of items, counted by the chapter’s functions for n from 10 to 200: the top curve bends upwards, the bottom one is almost flat.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-searching-and-sorting/fig-74ea7a32f8cc.svg)

*[Comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) against the number of [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), counted by the chapter’s [functions](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) for $n$ from 10 to 200: the top curve bends upwards, the bottom one is almost flat.*

When the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) doubles, $n(n-1)/2$ is about four times larger: the top curve bends upwards. A [linear search](#def-g8-searching-and-sorting-linear-search) on a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) twice as long only works twice as much. Book 2 makes this way of comparing methods precise.

**Remark 28.6 (Sorting in practice).**

Python has a sort built in: `sorted(items)` returns a new [sorted list](#def-g8-searching-and-sorting-sorted), and `items.sort()` sorts a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) in place. They use a cleverer method than the two of this chapter, and are the tools to use in real [programs](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program). Writing the two sorts by hand shows what such a tool does, and how to count its work.

## 28.6 Exercises

**Exercise 28.1 ★.**

[Binary search](#def-g8-searching-and-sorting-binary-search) looks for 37 in the [sorted list](#def-g8-searching-and-sorting-sorted) `[3, 8, 15, 21, 29, 37, 44, 50, 61]`. Write `low`, `middle`, `high` and the middle [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) at each step.

**Solution of Exercise 28.1.**

Step 1: `low` 0, `high` 8, `middle` 4, [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) 29, smaller than 37, so `low` becomes 5. Step 2: `low` 5, `high` 8, `middle` 6, [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) 44, larger, so `high` becomes 5. Step 3: `low` 5, `high` 5, `middle` 5, [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) 37: found at position 5, in 3 steps.

**Exercise 28.2 ★.**

Write the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) `[6, 2, 8, 5, 1]` after the first two passes of [selection sort](#def-g8-searching-and-sorting-selection-sort).

**Solution of Exercise 28.2.**

Pass 1 swaps the smallest, 1, with 6: `[1, 2, 8, 5, 6]`. Pass 2 finds that the smallest of the rest, 2, is already in place: `[1, 2, 8, 5, 6]`.

**Exercise 28.3 ★.**

Write the same [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) `[6, 2, 8, 5, 1]` after the first two passes of [insertion sort](#def-g8-searching-and-sorting-insertion-sort).

**Solution of Exercise 28.3.**

Pass 1 slides 2 before 6: `[2, 6, 8, 5, 1]`. Pass 2 leaves 8 where it is, since 6 is smaller: `[2, 6, 8, 5, 1]`.

**Exercise 28.4 ★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `all_positions(items, target)` that returns the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of all the positions where `target` appears, and an empty [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) if it does not.

**Solution of Exercise 28.4.**

A [linear search](#def-g8-searching-and-sorting-linear-search) that does not stop at the first match:

```python
def all_positions(items, target):
    positions = []
    for i in range(len(items)):
        if items[i] == target:
            positions.append(i)
    return positions


print(all_positions([12, 9, 15, 11, 9, 14, 13, 9], 9), all_positions([1, 2], 5))
```

*All the positions of a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value). code/grade-8/04-searching-and-sorting/exercises/all_positions.py*

**Exercise 28.5 ★★.**

This version of [binary search](#def-g8-searching-and-sorting-binary-search) never ends when it looks for 2 in `[4, 9]`. Follow `low` and `high` by hand to see why, and fix it.

```python
def binary_search(items, target):
    low = 0
    high = len(items) - 1
    while low <= high:
        middle = (low + high) // 2
        if items[middle] == target:
            return middle
        elif items[middle] < target:
            low = middle + 1
        else:
            high = middle
    return -1


print(binary_search([4, 9], 2))
```

***Listing 28.8.** A [binary search](#def-g8-searching-and-sorting-binary-search) that can [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) forever. code/grade-8/04-searching-and-sorting/exercises/binary_bug.py*

**Solution of Exercise 28.5.**

`low` 0, `high` 1, `middle` 0: 4 is larger than 2, so `high` becomes 0. Then `low` 0, `high` 0, `middle` 0: 4 is larger again, and `high` becomes 0 again. Nothing changes any more, and `low <= high` stays true forever. The middle [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) has already been compared, so it must be left out: `high = middle - 1`. Then each step makes the part searched smaller, and the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) ends.

**Exercise 28.6 ★★.**

This [insertion sort](#def-g8-searching-and-sorting-insertion-sort) prints `[5, 1, 3]`. Which [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) does it forget, and how do you fix it?

```python
def insertion_sort(items):
    for i in range(2, len(items)):
        j = i
        while j > 0 and items[j - 1] > items[j]:
            items[j - 1], items[j] = items[j], items[j - 1]
            j = j - 1


cards = [5, 1, 3]
insertion_sort(cards)
print(cards)
```

***Listing 28.9.** An [insertion sort](#def-g8-searching-and-sorting-insertion-sort) that misses an [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). code/grade-8/04-searching-and-sorting/exercises/insertion_bug.py*

**Solution of Exercise 28.6.**

`range(2, len(items))` starts at position 2, so the [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) at position 1 (here 1) is never slid back. Starting at 1, `range(1, len(items))`, sorts the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list): `[1, 3, 5]`.

**Exercise 28.7 ★★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that uses `binary_search` from [Listing 28.2](#lst-g8-searching-and-sorting-binary) to find the largest number of guesses it needs for a target between 1 and 1,000, trying every target. Check the answer with powers of two.

**Solution of Exercise 28.7.**

Saved in the [folder](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-folder) of [Listing 28.2](#lst-g8-searching-and-sorting-binary), the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) imports its `binary_search`:

```python
from binary_search import binary_search

numbers = list(range(1, 1001))
most = 0
for target in numbers:
    position, guesses = binary_search(numbers, target)
    if guesses > most:
        most = guesses
print("at most", most, "guesses for 1 to 1000")
```

*The most guesses between 1 and 1,000. code/grade-8/04-searching-and-sorting/exercises/max_guesses.py*

It prints `at most 10 guesses for 1 to 1000`. Indeed 9 guesses cover only $2^9 - 1 = 511$ [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), and 10 cover $2^{10} - 1 = 1{,}023$.

**Exercise 28.8 ★★.**

Write your own [selection sort](#def-g8-searching-and-sorting-selection-sort) that sorts a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of words from the shortest to the longest.

**Solution of Exercise 28.8.**

The [selection sort](#def-g8-searching-and-sorting-selection-sort) of the chapter, comparing `len` of the words:

```python
def sort_by_length(words):
    """Selection sort, comparing the lengths of the words."""
    for start in range(len(words) - 1):
        shortest = start
        for i in range(start + 1, len(words)):
            if len(words[i]) < len(words[shortest]):
                shortest = i
        words[start], words[shortest] = words[shortest], words[start]


words = ["banana", "fig", "cherry", "kiwi", "apple"]
sort_by_length(words)
print(words)
```

*Words from the shortest. code/grade-8/04-searching-and-sorting/exercises/by_length.py*

It prints `['fig', 'kiwi', 'apple', 'banana', 'cherry']`.

**Exercise 28.9 ★★.**

Count by hand the [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) of [selection sort](#def-g8-searching-and-sorting-selection-sort) on 5 [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), pass by pass. Does it depend on the order of the [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list)?

**Solution of Exercise 28.9.**

Pass 1 compares the smallest found so far with each of the 4 other [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list); pass 2 with the 3 after the first place, then 2, then 1: $4 + 3 + 2 + 1 = 10$ [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison). It does not depend on the order: [selection sort](#def-g8-searching-and-sorting-selection-sort) always looks at the whole rest of the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) to be sure it has the smallest.

**Exercise 28.10 ★★★.**

Find a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of 3 numbers that contains 5 but on which [binary search](#def-g8-searching-and-sorting-binary-search) does not find 5. Explain why [binary search](#def-g8-searching-and-sorting-binary-search) needs a [sorted list](#def-g8-searching-and-sorting-sorted).

**Solution of Exercise 28.10.**

`[5, 1, 3]`: the middle [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is 1, smaller than 5, so the search goes right; it finds 3, still smaller, goes right again, and stops with $-1$. [Binary search](#def-g8-searching-and-sorting-binary-search) throws away a half without looking at it; that is safe only if the order guarantees that the target cannot be there.

**Exercise 28.11 ★★★.**

Show that [insertion sort](#def-g8-searching-and-sorting-insertion-sort) makes exactly $n - 1$ [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) on a [sorted list](#def-g8-searching-and-sorting-sorted) of $n$ [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), and exactly $n(n-1)/2$ on a reversed one. Count the [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) of each pass, then add them up.

**Solution of Exercise 28.11.**

Pass $i$ (for $i$ from 1 to $n - 1$) slides the [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) at position $i$. On a [sorted list](#def-g8-searching-and-sorting-sorted) it is compared once with the [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) before it, which is smaller, and stays: one [comparison](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) per pass, $n - 1$ in all. On a reversed [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) it is smaller than all the $i$ [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) before it, so it is compared with each of them and slides to the front: $i$ [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison). In all, $1 + 2 + \dots + (n - 1)$. Writing this sum twice, once forwards and once backwards, gives $n - 1$ pairs that each add up to $n$, so the sum is $n(n-1)/2$.

**Exercise 28.12 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `sort_books(books)` that sorts the records of the town’s book table ([Chapter 27](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#ch-g8-files-and-data-tables)) by year, and by title for books of the same year, with your own [insertion sort](#def-g8-searching-and-sorting-insertion-sort).

**Solution of Exercise 28.12.**

A helper [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) decides which of two books comes first; the [insertion sort](#def-g8-searching-and-sorting-insertion-sort) uses it in place of `>`:

```python
def comes_before(a, b):
    """True when book a goes before book b: older first, then by title."""
    if int(a["year"]) != int(b["year"]):
        return int(a["year"]) < int(b["year"])
    return a["title"] < b["title"]


def sort_books(books):
    """Insertion sort of a list of book records, in place."""
    for i in range(1, len(books)):
        j = i
        while j > 0 and comes_before(books[j], books[j - 1]):
            books[j - 1], books[j] = books[j], books[j - 1]
            j = j - 1
```

*The books by year, then by title. code/grade-8/04-searching-and-sorting/exercises/sort_books.py*

A test of the chapter checks it on records with the same year.

## 28.7 Problem: One Word among a Million

**Problem 28.1.**

Weekend problem — finding one word among a million

A [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) of a million words is kept as a [sorted list](#def-g8-searching-and-sorting-sorted). How many [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) does it take to find a word, and is it worth sorting first?

**Part I — By hand.**

1. Between 1 and 16, guess the secret number 11 by halving: write each guess and the part left.
2. Halve 1,000 again and again, keeping the larger half, until one [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is left. How many halvings is that?
3. Why does halving help only when the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is [sorted](#def-g8-searching-and-sorting-sorted) ?

**Part II — The worst case, by program.**

```python
def worst_guesses(n):
    """Guesses of binary search on n items, the target always in the larger half."""
    low = 0
    high = n - 1
    guesses = 0
    while low <= high:
        middle = (low + high) // 2
        guesses = guesses + 1
        low = middle + 1            # the right half is never smaller than the left
    return guesses


n = 10
while n <= 1_000_000:
    print(f"{n:>9} items: {worst_guesses(n)} guesses at most")
    n = n * 10
```

***Listing 28.10.** The largest number of guesses for [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of 10 to a million [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). code/grade-8/04-searching-and-sorting/listings/worst_guesses.py*

4. Why does `worst_guesses` always set `low = middle + 1` ?
5. Run the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) . How do the counts grow when the size is multiplied by 10?
6. Explain the 20 for a million with a power of two.
7. How many [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) would a [linear search](#def-g8-searching-and-sorting-linear-search) need in the worst case for a million words?

**Part III — Sorting first.**

```python
from binary_search import binary_search
from count_comparisons import mixed
from insertion_sort import insertion_sort
from linear_search import linear_search
from selection_sort import selection_sort

n = 1000
words = mixed(n)            # 1,000 "words", numbered 0 to 999, in a mixed order

scan = 0
for target in range(n):
    position, comparisons = linear_search(words, target)
    scan = scan + comparisons
print("1,000 linear searches:", scan, "comparisons")

by_selection = selection_sort(list(words))
by_insertion = insertion_sort(list(words))
sorted_words = sorted(words)
halving = 0
for target in range(n):
    position, guesses = binary_search(sorted_words, target)
    halving = halving + guesses
print("selection sort:", by_selection, "+ 1,000 binary searches:", halving)
print("insertion sort:", by_insertion, "+ 1,000 binary searches:", halving)
```

***Listing 28.11.** 1,000 searches without and with sorting first. code/grade-8/04-searching-and-sorting/listings/sort_or_scan.py*

8. What does the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) compare?
9. Run it. What do the 1,000 [linear searches](#def-g8-searching-and-sorting-linear-search) cost, and what do sorting plus 1,000 [binary searches](#def-g8-searching-and-sorting-binary-search) cost?
10. With [selection sort](#def-g8-searching-and-sorting-selection-sort) , is sorting first worth it for 1,000 searches? With [insertion sort](#def-g8-searching-and-sorting-insertion-sort) ?
11. What if the [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) is searched 100,000 times, and [sorted](#def-g8-searching-and-sorting-sorted) only once?
12. State the result.

**Solution of Problem 28.1.**

**1.** Guess 8: higher, 9 to 16 left. Guess 12: lower, 9 to 11 left. Guess 10: higher, 11 left. Guess 11: found, in 4 guesses.

**2.** 1,000, 500, 250, 125, 63, 32, 16, 8, 4, 2, 1: ten halvings, so about 10 guesses.

**3.** Throwing away half of the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is safe only if the order says the target cannot be there.

**4.** Going right keeps the larger half, since `//` rounds down: it is the case where the most guesses are needed.

**5.** Each time the size is multiplied by 10, 3 or 4 more guesses are needed:

```
$ python worst_guesses.py
       10 items: 4 guesses at most
      100 items: 7 guesses at most
     1000 items: 10 guesses at most
    10000 items: 14 guesses at most
   100000 items: 17 guesses at most
  1000000 items: 20 guesses at most
```

***Output 28.8.** The worst case, from 10 to a million [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list).*

Multiplying by 10 is a little more than three doublings, since $2^3 = 8 < 10 < 16 = 2^4$.

**6.** 19 guesses cover $2^{19} - 1 = 524{,}287$ [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), not enough; 20 cover $2^{20} - 1 = 1{,}048{,}575$, which is at least a million.

**7.** A million: every word is looked at when the word sought is last or absent.

**8.** The cost of 1,000 [linear searches](#def-g8-searching-and-sorting-linear-search) in a mixed [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), against the cost of sorting the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) once and then making 1,000 [binary searches](#def-g8-searching-and-sorting-binary-search).

**9.**

```
$ python sort_or_scan.py
1,000 linear searches: 500500 comparisons
selection sort: 499500 + 1,000 binary searches: 8987
insertion sort: 252747 + 1,000 binary searches: 8987
```

***Output 28.9.** [Comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) without and with sorting.*

The [linear searches](#def-g8-searching-and-sorting-linear-search) cost 500,500 [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison). Sorting costs 499,500 with [selection sort](#def-g8-searching-and-sorting-selection-sort) and 252,747 with [insertion sort](#def-g8-searching-and-sorting-insertion-sort); the 1,000 [binary searches](#def-g8-searching-and-sorting-binary-search) add only 8,987.

**10.** With [selection sort](#def-g8-searching-and-sorting-selection-sort), $499{,}500 + 8{,}987 = 508{,}487$, a little more than the 500,500 of the [linear searches](#def-g8-searching-and-sorting-linear-search): not worth it. With [insertion sort](#def-g8-searching-and-sorting-insertion-sort), $252{,}747 + 8{,}987 = 261{,}734$, about half: worth it.

**11.** The sort is paid once, and each [binary search](#def-g8-searching-and-sorting-binary-search) costs about 9 [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) instead of about 500. 100,000 [linear searches](#def-g8-searching-and-sorting-linear-search) cost about 50 million [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison); 100,000 [binary searches](#def-g8-searching-and-sorting-binary-search) about 900,000, plus one sort. Sorting first wins by far.

**12.** **Result.** [Binary search](#def-g8-searching-and-sorting-binary-search) finds any word among 1,000,000 [sorted](#def-g8-searching-and-sorting-sorted) words in at most 20 [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison), because $2^{20} = 1{,}048{,}576$ is at least 1,000,000; a [linear search](#def-g8-searching-and-sorting-linear-search) may need a million. Sorting costs more than one search, but it is paid once: as soon as the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is searched many times, sorting first wins.
