Skip to content

Selection sort

ordering

Level 1 of 3

Also called Straight selection.

how it works

The idea in a few sentences and three pictures, then one row sorted step by step.

Selection sort puts a row of numbers in order, smallest first, one place at a time from the left. To fill a place, a pass looks along the numbers not yet placed. Each one after the place is compared with the smallest so far. Then the smallest swaps into the place, where it stays. If it is already home, nothing moves. The last place needs no pass: the number left is the biggest. A swap can carry a number past an equal one. On 2, 2, 1 the first 2 ends up after the second, so equal numbers may change order.

looks atsmallest so far
5, the start5
85
33
93
43
Pass 1 on 5, 8, 3, 9, 4. The smallest so far starts as the 5, and 4 comparisons find the 3. The 3 then swaps with the 5, giving 3, 8, 5, 9, 4.
the row42, 7, 31, 18, 56, 23, 12, 49
after pass 17, 42, 31, 18, 56, 23, 12, 49
after pass 27, 12, 31, 18, 56, 23, 42, 49
after pass 37, 12, 18, 31, 56, 23, 42, 49
after pass 47, 12, 18, 23, 56, 31, 42, 49
after pass 57, 12, 18, 23, 31, 56, 42, 49
after pass 67, 12, 18, 23, 31, 42, 56, 49
after pass 77, 12, 18, 23, 31, 42, 49, 56
The row of the run below, after each pass. Pass 1 meets the 7 at once, yet still compares the six numbers after it. Here every pass swaps. 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28 comparisons and 7 swaps.
2a2b1the row12b2aafter pass 112b2aafter pass 2
The thick lines follow the two 2s, told apart as 2a and 2b; the dotted line follows the 1. Pass 1 swaps the 1 into place 1, carrying 2a past 2b. Pass 2 swaps nothing, as 2 is not smaller than 2, so they end in the other order. That matters when the 2s stand for different things, such as two people of the same age.
A short shuffle: 8 moments of its 61 steps, the steps between them left for the watch page
  1. step 2 of 61

    427311856231249

    Start with 42, the number already in this place: it is the smallest so far.

    what it remembers to know where it is
    filling place
    1
    smallest so far
    42
    looking at position
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 4 of 61

    427311856231249

    7 is the smallest so far now.

    what it remembers to know where it is
    filling place
    1
    smallest so far
    7
    looking at position
    2

    watch from here

  3. step 11 of 61

    742311856231249

    Swap 7 into the place, and 42 goes where 7 was.

    what it remembers to know where it is
    filling place
    1
    smallest so far
    7
    looking at position
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  4. step 12 of 61

    742311856231249

    7 is in its place for good: nothing smaller is left.

    what it remembers to know where it is
    filling place
    1
    smallest so far
    7
    looking at position
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  5. step 21 of 61

    742311856231249

    12 is the smallest so far now.

    what it remembers to know where it is
    filling place
    2
    smallest so far
    12
    looking at position
    7

    watch from here

  6. step 24 of 61

    712311856234249

    12 is in its place for good: nothing smaller is left.

    what it remembers to know where it is
    filling place
    2
    smallest so far
    12
    looking at position
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  7. step 48 of 61

    712182331564249

    31 is in its place for good: nothing smaller is left.

    what it remembers to know where it is
    filling place
    5
    smallest so far
    31
    looking at position
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  8. step 61 of 61

    712182331424956

    In order, after 28 comparisons and 7 swaps.

    what it remembers to know where it is
    filling place
    8
    smallest so far
    not yet
    looking at position
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. for each place from the left, all but the lastPython line 9
  2. the smallest so far is the number in that placePython line 10
  3. look at each number after itPython line 11
  4. if it is smaller, it is the smallest so farPython lines 12 and 13
  5. swap the smallest so far into the place, where it staysPython lines 14 and 15
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def selection_sort(numbers):
    """Put a list of numbers in order, smallest first, in the list itself.

    For each place from the left, all but the last, find the smallest of
    the numbers not yet placed, and swap that one into the place,
    where it stays. A number already in its place is not swapped. The list
    is sorted where it stands, with no copy made, and handed back.
    """
    for place in range(len(numbers) - 1):  # every place but the last
        smallest = place  # the smallest so far is the number in that place
        for i in range(place + 1, len(numbers)):  # look at each number after it
            if numbers[i] < numbers[smallest]:
                smallest = i  # a smaller one: it is the smallest so far
        if smallest != place:
            numbers[place], numbers[smallest] = numbers[smallest], numbers[place]  # swap it in
    return numbers

how it scales

How the comparisons grow, from ten numbers to ten million.

Each step across or up is ten times the one before, a log-log plot. Every row of nn numbers makes the same comparisons, n(n−1)2\frac{n(n - 1)}{2}, so rows in order, shuffled and with the smallest moved last draw one line. It climbs two steps up for each step across: 45 comparisons at 10 numbers, 4,950 at 100. Ten times the numbers, about a hundred times the comparisons. Section 4 shows why.

comparisons, ten times more at each mark up

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

nn, how many numbers are in the row, ten times more at each mark to the right

  • different numbers in order but for the smallest, moved last, such as 2, 4, 6, 8, 1, a row where every pass swapssolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • shuffled, different numbers in a random order, every order as likelysolid where measured by running it; dashed where its formula carries it on to ten million
  • already in order, the only kind of row with no swapsolid where measured by running it; dashed where its formula carries it on to ten million
what a dearest row costs, at a billion comparisons a second
nncomparisonstime
1,000499,500about 500 microseconds
100,0004,999,950,000about 5 seconds
10,000,00049,999,995,000,000about 14 hours

The comparisons are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count selection sort's comparisons yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it prints the comparisons
on a row already in order, on the even numbers in order then a 1 (2, 4, 6,
8, 1 for five), and the average over 20 shuffles. Every row of one size
makes the same comparisons, so the three columns agree. The counts are the
same on any computer; only the time taken differs.
"""
import random


class Counted:
    """A number that counts every comparison made with it."""

    comparisons = 0

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

    def __lt__(self, other):
        Counted.comparisons += 1
        return self.value < other.value


def selection_sort(numbers):
    """Put a list of numbers in order, smallest first, in the list itself.

    For each place from the left, all but the last, find the smallest of
    the numbers not yet placed, and swap that one into the place,
    where it stays. A number already in its place is not swapped. The list
    is sorted where it stands, with no copy made, and handed back.
    """
    for place in range(len(numbers) - 1):  # every place but the last
        smallest = place  # the smallest so far is the number in that place
        for i in range(place + 1, len(numbers)):  # look at each number after it
            if numbers[i] < numbers[smallest]:
                smallest = i  # a smaller one: it is the smallest so far
        if smallest != place:
            numbers[place], numbers[smallest] = numbers[smallest], numbers[place]  # swap it in
    return numbers


def count(row):
    """How many comparisons selection sort makes on this row."""
    Counted.comparisons = 0
    selection_sort([Counted(x) for x in row])
    return Counted.comparisons


if __name__ == "__main__":
    random.seed(1)
    print(f"{'n':>6} {'in order':>10} {'smallest last':>14} {'shuffled':>10}")
    for n in [10, 100, 1000]:
        shuffles = []
        for _ in range(20):
            row = list(range(1, n + 1))
            random.shuffle(row)
            shuffles.append(count(row))
        in_order = count(list(range(1, n + 1)))
        smallest_last = count([2 * i for i in range(1, n)] + [1])
        print(f"{n:>6} {in_order:>10} {smallest_last:>14} {sum(shuffles) / 20:>10.1f}")

best, worst and average

Every row costs the same comparisons. Only the swaps change, at most one per pass. A row with no swap is in order, since every pass found its smallest at home. Many rows swap at every pass, such as 4, 1, 2, 3 and 2, 4, 6, 8, 1.

A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestalready in order, the only kind of row with no swapaverageshuffled, different numbers in a random order, every order as likelyworstdifferent numbers in order but for the smallest, moved last, such as 2, 4, 6, 8, 1, a row where every pass swaps
comparisonsn(n−1)2\frac{n(n - 1)}{2}n(n−1)2\frac{n(n - 1)}{2}n(n−1)2\frac{n(n - 1)}{2}
swapsnonen−H(n)n - H(n)n−1n - 1
how the comparisons grow in each case
tight, Θ\ThetaΘ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)
ceiling, OOO(n2)O(n^2)O(n2)O(n^2)O(n2)O(n^2)
floor, Ω\OmegaΩ(n2)\Omega(n^2)Ω(n2)\Omega(n^2)Ω(n2)\Omega(n^2)

extra memory: room for a few numbers (the place being filled, where the smallest so far stands, the number looked at, one held during a swap), the same however long the row

Extra memory is the room it needs on top of the input itself, while it runs.

row of 5comparisonsswaps
1, 2, 3, 4, 5100
5, 4, 3, 2, 1102
2, 4, 6, 8, 1104
all 120 orders, on average10about 2.72
Every row of 5 makes 4 + 3 + 2 + 1 = 10 comparisons. In order, no pass swaps; on 2, 4, 6, 8, 1 all 4 do. 5 numbers stand in 5 × 4 × 3 × 2 × 1 = 120 orders, 5 choices for place 1, then 4, and on. They average about 2.72 swaps, section 4's n−H(n)n - H(n) for 5. H(5)H(5) is 1 + a half + a third + a quarter + a fifth, about 2.28, and 5 less 2.28 is about 2.72.
the row5, 4, 3, 2, 1
after swap 11, 4, 3, 2, 5
after swap 21, 2, 3, 4, 5
Back to front, pass 1 swaps the 1 and the 5, putting both home. Pass 2 does the same for the 2 and the 4. Passes 3 and 4 find their smallest at home, so 2 swaps in all.

where the formula comes from

Each count above, worked out in small steps, one ladder of numbered lines per count. Every step names the line it uses.

Why does every row of nn numbers take n(n−1)2\frac{n(n - 1)}{2} comparisons?
  1. the move: count one pass

    the line:
    the pass that fills place kmakes n−k comparisons\begin{gathered} \text{the pass that fills place } k \\ \text{makes } n - k \text{ comparisons} \end{gathered}

    why it is allowed: Each of the n−kn - k numbers after place kk is compared once. On 5, 8, 3, 9, 4, pass 2 compares 3 numbers, 5 less 2. Their order never changes how many.

  2. the move: count the passes

    the line:
    there are n−1 passes,for places 1 to n−1\begin{gathered} \text{there are } n - 1 \text{ passes,} \\ \text{for places 1 to } n - 1 \end{gathered}

    why it is allowed: Once places 1 to n−1n - 1 hold the smallest numbers, the one left is the biggest, already at place nn.

  3. the move: add up the passes

    the line:
    C=(n−1)+(n−2)+⋯+1C = (n - 1) + (n - 2) + \dots + 1

    why it is allowed: CC is the comparisons on any row of nn numbers, line 1 added over line 2's passes. For 4 numbers, 3 + 2 + 1.

  4. the move: add them the other way round

    the line:
    C=1+2+⋯+(n−1)C = 1 + 2 + \dots + (n - 1)

    why it is allowed: The same numbers in the other order. For 4 numbers, 1 + 2 + 3 is 3 + 2 + 1, 6.

  5. the move: use the page on adding up, for a sum that stops at n - 1

    the line:
    C=(n−1)((n−1)+1)2C = \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2}
    where does this come from?
    question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
    1. the move: draw the sum as a staircase

      the line:
      S=1+2+⋯+nS = 1 + 2 + \dots + n

      why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

    2. the move: take two staircases

      the line:
      2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

      why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

    3. the move: fit them into a rectangle

      the line:
      2S=n(n+1)2S = n(n + 1)
      Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

      why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

    4. the move: halve both sides

      the line:
      S=n(n+1)2S = \frac{n(n + 1)}{2}

      why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

    the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

    why it is allowed: Line 4's sum ends at n−1n - 1. The box above shows 1 + 2 + ... + 5 is 5 times 6, halved, and the same for any last number. For 4 numbers, 3 times 4, halved, is 6.

  6. the move: tidy the bracket

    the line:
    C=(n−1)n2C = \frac{(n - 1)n}{2}

    why it is allowed: One more than n−1n - 1 is nn.

  7. the move: write the product the other way round

    the line:
    C=n(n−1)2C = \frac{n(n - 1)}{2}

    why it is allowed: The same product.

  8. the move: multiply out the bracket

    the line:
    C=n2−n2C = \frac{n^2 - n}{2}

    why it is allowed: nn lots of nn make n2n^2, and nn lots of 1 make nn. For 4 numbers, 4 times 3 is 12, which is 16 less 4.

  9. the move: halve each part

    the line:
    C=n22−n2C = \frac{n^2}{2} - \frac{n}{2}

    why it is allowed: Half of a difference is the difference of the halves.

  10. the move: a ceiling

    the line:
    C≤n22C \le \frac{n^2}{2}

    why it is allowed: Line 9 takes something away from n22\frac{n^2}{2}. For 4 numbers, 6 is at most 8, half of 16.

  11. the move: read it as a bound

    the line:
    C∈O(n2)C \in O(n^2)

    why it is allowed: By line 10, CC stays under a fixed multiple of n2n^2, a half.

  12. the move: a fact about n

    the line:
    n≤n22 for n≥2n \le \frac{n^2}{2} \text{ for } n \ge 2

    why it is allowed: Now a floor. n22\frac{n^2}{2} is nn times half of nn, and half of nn is at least 1 from 2 numbers on. For 10 numbers, 10 is at most 50.

  13. the move: a fact for the floor, halving both sides

    the line:
    n2≤n24 for n≥2\frac{n}{2} \le \frac{n^2}{4} \text{ for } n \ge 2
    nnn2\frac{n}{2}n24\frac{n^2}{4}
    211
    424
    10525
    100502,500
    Equal at 2 numbers, then the quarter of n squared pulls ever further ahead.

    why it is allowed: Line 12 with both sides halved. For 10 numbers, 5 is at most 25, so line 14 can take away 25 instead of line 9's 5, a part made of n2n^2 alone.

  14. the move: a floor

    the line:
    C≥n22−n24 for n≥2C \ge \frac{n^2}{2} - \frac{n^2}{4} \text{ for } n \ge 2

    why it is allowed: For 10 numbers, 45 is at least 50 less 25. Line 9 takes away n2\frac{n}{2}; line 13's n24\frac{n^2}{4} is at least that, and taking away more leaves less.

  15. the move: tidy the floor

    the line:
    C≥n24 for n≥2C \ge \frac{n^2}{4} \text{ for } n \ge 2

    why it is allowed: Half less a quarter is a quarter.

  16. the move: read it as a bound

    the line:
    C∈Ω(n2)C \in \Omega(n^2)
    nnfloor, n24\frac{n^2}{4}CCceiling, n22\frac{n^2}{2}
    2112
    4468
    10254550
    1002,5004,9505,000
    From 2 numbers on, CC sits between a quarter and a half of n2n^2. That squeeze is Θ(n2)\Theta(n^2).

    why it is allowed: By line 15, CC stays at or above a fixed multiple of n2n^2, a quarter, from 2 numbers on. A floor need only hold for rows long enough; at 1 number CC is 0.

  17. the move: a ceiling and a floor together

    the line:
    C∈Θ(n2)C \in \Theta(n^2)

    why it is allowed: Lines 16 and 11 bound CC by the same growth, n2n^2.

try it with a small nn: at n=4n = 4, line 3 gives C=6C = 6, which you can work out by hand

Why does a row already in order take the same n(n−1)2\frac{n(n - 1)}{2} comparisons?
  1. the move: every pass still looks at every number left

    the line:
    on a row in order, the pass forplace k still makes n−kcomparisons\begin{gathered} \text{on a row in order, the pass for} \\ \text{place } k \text{ still makes } n - k \\ \text{comparisons} \end{gathered}
    passlooks atcomparisonsswap
    12, 3, 4, 54no
    23, 4, 53no
    34, 52no
    451no
    On 1, 2, 3, 4, 5 every smallest is at home, yet each pass compares it with every number after it, 4 + 3 + 2 + 1 = 10.

    why it is allowed: The number at place kk is already the smallest left, but the pass learns that only by comparing it with all n−kn - k numbers after it.

  2. the move: add up the passes

    the line:
    B=(n−1)+(n−2)+⋯+1B = (n - 1) + (n - 2) + \dots + 1

    why it is allowed: BB is the comparisons on a row in order, line 1 added over the first ladder's n−1n - 1 passes. For 4 numbers, 3 + 2 + 1.

  3. the move: add them the other way round

    the line:
    B=1+2+⋯+(n−1)B = 1 + 2 + \dots + (n - 1)

    why it is allowed: The same numbers in the other order.

  4. the move: use the page on adding up, for a sum that stops at n - 1

    the line:
    B=(n−1)((n−1)+1)2B = \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2}
    where does this come from?
    question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
    1. the move: draw the sum as a staircase

      the line:
      S=1+2+⋯+nS = 1 + 2 + \dots + n

      why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

    2. the move: take two staircases

      the line:
      2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

      why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

    3. the move: fit them into a rectangle

      the line:
      2S=n(n+1)2S = n(n + 1)
      Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

      why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

    4. the move: halve both sides

      the line:
      S=n(n+1)2S = \frac{n(n + 1)}{2}

      why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

    the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

    why it is allowed: As in the first ladder's line 5.

  5. the move: tidy the bracket

    the line:
    B=(n−1)n2B = \frac{(n - 1)n}{2}

    why it is allowed: One more than n−1n - 1 is nn.

  6. the move: write the product the other way round

    the line:
    B=n(n−1)2B = \frac{n(n - 1)}{2}

    why it is allowed: The same product. It is the first ladder's formula, so that ladder's lines 8 to 17 hold here too, and a row in order costs Θ(n2)\Theta(n^2).

try it with a small nn: at n=4n = 4, line 2 gives B=6B = 6, which you can work out by hand

Why does a shuffled row take n(n−1)2\frac{n(n - 1)}{2} comparisons on average?
  1. the move: every shuffle costs the same

    the line:
    every shuffle of n numbers makesthe same comparisons\begin{gathered} \text{every shuffle of } n \text{ numbers makes} \\ \text{the same comparisons} \end{gathered}
    shufflecomparisons
    1, 2, 33
    1, 3, 23
    2, 1, 33
    2, 3, 13
    3, 1, 23
    3, 2, 13
    in all18
    average3
    Every shuffle of 1, 2 and 3 makes 2 + 1 = 3 comparisons, so the average is 3 too.

    why it is allowed: A shuffle is a row, and by the first ladder's line 3 every row of nn numbers makes the same sum, whatever its order.

  2. the move: average a count that never changes

    the line:
    A=(n−1)+(n−2)+⋯+1A = (n - 1) + (n - 2) + \dots + 1

    why it is allowed: AA is the comparisons averaged over every shuffle of nn different numbers. One count added once per shuffle, then divided by the shuffles, gives that count back. 3 numbers have 3 × 2 × 1 = 6 shuffles, 3 choices for place 1, then 2, then 1. They make 18 comparisons in all, and 18 over 6 is 3.

  3. the move: add them the other way round

    the line:
    A=1+2+⋯+(n−1)A = 1 + 2 + \dots + (n - 1)

    why it is allowed: The same numbers in the other order.

  4. the move: use the page on adding up, for a sum that stops at n - 1

    the line:
    A=(n−1)((n−1)+1)2A = \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2}
    where does this come from?
    question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
    1. the move: draw the sum as a staircase

      the line:
      S=1+2+⋯+nS = 1 + 2 + \dots + n

      why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

    2. the move: take two staircases

      the line:
      2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

      why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

    3. the move: fit them into a rectangle

      the line:
      2S=n(n+1)2S = n(n + 1)
      Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

      why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

    4. the move: halve both sides

      the line:
      S=n(n+1)2S = \frac{n(n + 1)}{2}

      why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

    the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

    why it is allowed: As in the first ladder's line 5.

  5. the move: tidy the bracket

    the line:
    A=(n−1)n2A = \frac{(n - 1)n}{2}

    why it is allowed: One more than n−1n - 1 is nn.

  6. the move: write the product the other way round

    the line:
    A=n(n−1)2A = \frac{n(n - 1)}{2}

    why it is allowed: The same product. It is the first ladder's formula, so that ladder's lines 8 to 17 hold here too, and the average is Θ(n2)\Theta(n^2).

try it on small rows: over every order of 4 numbers, the average is A=6A = 6

Why does a row already in order need no swap?
  1. the move: each pass finds its smallest at home

    the line:
    on a row in order, each pass findsits smallest already in its place\begin{gathered} \text{on a row in order, each pass finds} \\ \text{its smallest already in its place} \end{gathered}

    why it is allowed: Pass 1 finds the smallest at place 1 and swaps nothing, so the row stays in order. Then pass 2 finds the next at place 2, and on.

  2. the move: count the swaps

    the line:
    Z=0Z = 0

    why it is allowed: ZZ is the swaps on a row in order. A pass swaps only when its smallest is away from home, which line 1 rules out.

try it with a small nn: at n=4n = 4, line 2 gives Z=0Z = 0, which you can work out by hand

Why does selection sort make at most n−1n - 1 swaps, and which rows make them all?
  1. the move: one swap at most per pass

    the line:
    each pass makesat most one swap\begin{gathered} \text{each pass makes} \\ \text{at most one swap} \end{gathered}

    why it is allowed: A pass ends with one swap of its smallest into its place, or none when it is already home.

  2. the move: no row makes more

    the line:
    no row of n numbers makesmore than n−1 swaps\begin{gathered} \text{no row of } n \text{ numbers makes} \\ \text{more than } n - 1 \text{ swaps} \end{gathered}

    why it is allowed: The first ladder's line 2 counts n−1n - 1 passes, and by line 1 each swaps at most once. For 4 numbers, 3.

  3. the move: on 2, 3, ..., n, 1, every pass swaps

    the line:
    on 2,3,…,n,1 everypass makes a swap\begin{gathered} \text{on } 2, 3, \dots, n, 1 \text{ every} \\ \text{pass makes a swap} \end{gathered}
    the row2, 4, 6, 1
    after pass 11, 4, 6, 2
    after pass 21, 2, 6, 4
    after pass 31, 2, 4, 6
    Each pass finds its smallest at the end of the row and swaps it home, sending the next number up to the end.

    why it is allowed: Only the order counts, so the picture's 2, 4, 6, 1 sorts as 2, 3, 4, 1 does. The smallest stands last, so pass 1 swaps it with the number at place 1, which goes last. That number is the smallest left, so pass 2 swaps it home, and on.

  4. the move: count the swaps

    the line:
    W=n−1W = n - 1
    nnmost swapscomparisons
    10945
    100994,950
    1,000999499,500
    Ten times the numbers makes about ten times the most swaps, but about a hundred times the comparisons.

    why it is allowed: WW is the swaps on that row, one for each of the n−1n - 1 passes by line 3, the most line 2 allows. For 4 numbers, 3.

  5. the move: a ceiling

    the line:
    W≤nW \le n

    why it is allowed: One less than nn is less than nn.

  6. the move: read it as a bound

    the line:
    W∈O(n)W \in O(n)

    why it is allowed: By line 5, WW stays under a fixed multiple of nn, 1 times.

  7. the move: a fact for the floor

    the line:
    1≤n2 for n≥21 \le \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: Half of nn is at least 1 from 2 numbers on. For 10 numbers, 1 is at most 5.

  8. the move: a floor

    the line:
    W≥n−n2 for n≥2W \ge n - \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: Line 4 takes away 1, at most line 7's n2\frac{n}{2}, and taking away more leaves less. For 10 numbers, 9 is at least 10 less 5.

  9. the move: tidy the floor

    the line:
    W≥n2 for n≥2W \ge \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: nn less half of nn is half of nn. For 10 numbers, 9 is at least 5.

  10. the move: read it as a bound

    the line:
    W∈Ω(n)W \in \Omega(n)

    why it is allowed: By line 9, from 2 numbers on.

  11. the move: a ceiling and a floor together

    the line:
    W∈Θ(n)W \in \Theta(n)

    why it is allowed: Lines 10 and 6 bound WW by the same growth, nn, while by the first ladder the comparisons grow like n2n^2.

try it with a small nn: at n=4n = 4, line 4 gives W=3W = 3, which you can work out by hand

How many swaps does a shuffled row of different numbers take, on average?
  1. the move: when a pass swaps

    the line:
    the pass for place kswaps unless the smallestof places k to n alreadystands at place k\begin{gathered} \text{the pass for place } k \\ \text{swaps unless the smallest} \\ \text{of places } k \text{ to } n \text{ already} \\ \text{stands at place } k \end{gathered}

    why it is allowed: By line 1 of the learn page's ladder on the most swaps, a pass swaps its smallest in unless it is already home. The numbers not yet placed stand at places kk to nn, which is n−k+1n - k + 1 places. Places 2 to 5 are 4 places, 5 less 2, plus 1.

  2. the move: what is left is still a shuffle

    the line:
    after a pass, the numbers leftstand in every orderequally often\begin{gathered} \text{after a pass, the numbers left} \\ \text{stand in every order} \\ \text{equally often} \end{gathered}
    shufflethe 1 at placeafter pass 1places 2 and 3
    1, 2, 311, 2, 32, 3
    2, 1, 321, 2, 32, 3
    3, 2, 131, 2, 32, 3
    1, 3, 211, 3, 23, 2
    3, 1, 221, 3, 23, 2
    2, 3, 131, 3, 23, 2
    Pass 1 on each shuffle of 1, 2 and 3, grouped by what it leaves. Each order of the 2 and the 3 comes from three shuffles, one for each place the 1 started at.

    why it is allowed: Undo pass 1's swap and the 1 goes back where it started. So each order of the rest comes from one shuffle per place the 1 could start at, nn in all. In the picture, 3, 2 comes from 1, 3, 2, from 3, 1, 2 and from 2, 3, 1. So the next pass meets a fresh shuffle, one number shorter, and the same holds for it.

  3. the move: the chance of no swap

    the line:
    the pass for place kfinds its smallest at homewith chance 1n−k+1\begin{gathered} \text{the pass for place } k \\ \text{finds its smallest at home} \\ \text{with chance } \frac{1}{n - k + 1} \end{gathered}
    1 at place 11321232 shuffles1 at place 32313212 shuffles=1 at place 22133122 shuffles=
    Each arrow trades the two places underlined in red, pairing up the shuffles as they stand before sorting, and trading back undoes it. Each place holds the 1 in 2 of the 6 shuffles.

    why it is allowed: By lines 1 and 2 the n−k+1n - k + 1 numbers left are a shuffle. In 2, 3, 1, trading places 1 and 3 gives 1, 3, 2, and trading back undoes it. So each order with their smallest at one place pairs with one with it at the other. So it stands at each place equally often, and at place kk, the first, in 1 of every n−k+1n - k + 1 orders. In the picture the 1 is at each place in 2 of the 6 shuffles, a third.

  4. the move: the swaps are a sum of tallies

    the line:
    the swaps are a sum of tallies,one per pass, each 1 or 0\begin{gathered} \text{the swaps are a sum of tallies,} \\ \text{one per pass, each 1 or 0} \end{gathered}

    why it is allowed: Each pass gets a tally, 1 when it swaps and 0 when not. Adding a row's tallies counts its swaps.

  5. the move: average tally by tally

    the line:
    the average swapsare the sum ofthe tallies’ averages\begin{gathered} \text{the average swaps} \\ \text{are the sum of} \\ \text{the tallies' averages} \end{gathered}
    shufflepass 1pass 2swaps
    1, 2, 3000
    1, 3, 2011
    2, 1, 3101
    2, 3, 1112
    3, 1, 2112
    3, 2, 1101
    in all437
    average4 over 63 over 67 over 6
    Each pass's tally on every shuffle of 1, 2 and 3, and each row's swaps.

    why it is allowed: Total the swaps column, or total each pass's column and add. Each tally is counted once either way, and dividing by the shuffles keeps them equal. In the picture, 4 and 3 make 7, and 4 over 6 and 3 over 6 make 7 over 6.

  6. the move: a tally's average is its chance

    the line:
    the tally of the passfor place k averages toits chance of a swap\begin{gathered} \text{the tally of the pass} \\ \text{for place } k \text{ averages to} \\ \text{its chance of a swap} \end{gathered}

    why it is allowed: A column of 1s and 0s averages to its share of 1s. In line 5's picture pass 1 swaps in 4 of the 6 shuffles, two thirds, and pass 2 in 3, a half.

  7. the move: a swap or none

    the line:
    that chance is1−1n−k+1\begin{gathered} \text{that chance is} \\ 1 - \frac{1}{n - k + 1} \end{gathered}

    why it is allowed: A pass either swaps or not, so the two chances add to 1, and line 3 gives the chance of none. Two thirds is 1 less a third, and a half is 1 less a half.

  8. the move: add up the passes

    the line:
    E=(1−1n)+(1−1n−1)+⋯+(1−12)\begin{gathered} E = \left(1 - \frac{1}{n}\right) + \left(1 - \frac{1}{n - 1}\right) \\ + \dots + \left(1 - \frac{1}{2}\right) \end{gathered}

    why it is allowed: EE is the swaps averaged over every shuffle of nn different numbers. By lines 5 to 7, place 1 adds 1−1n1 - \frac{1}{n}, down to 1−121 - \frac{1}{2} for place n−1n - 1. For 3 numbers, two thirds plus a half, 7 over 6.

  9. the move: take the ones out

    the line:
    E=(n−1)−(1n+1n−1+⋯+12)\begin{gathered} E = (n - 1) \\ - \left(\frac{1}{n} + \frac{1}{n - 1} + \dots + \frac{1}{2}\right) \end{gathered}

    why it is allowed: n−1n - 1 brackets, each 1 less a fraction. The ones make n−1n - 1, and every fraction is taken away.

  10. the move: add the fractions the other way round

    the line:
    E=(n−1)−(12+13+⋯+1n)E = (n - 1) - \left(\frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{n}\right)

    why it is allowed: The same fractions in the other order.

  11. the move: name the sum

    the line:
    E=(n−1)−(H(n)−1)E = (n - 1) - \bigl(H(n) - 1\bigr)

    why it is allowed: 1, plus a half, and on up to 1 over nn, is the harmonic sum, H(n)H(n). This sum lacks its first 1.

  12. the move: open the bracket

    the line:
    E=(n−1)−H(n)+1E = (n - 1) - H(n) + 1

    why it is allowed: Taking away H(n)H(n) less 1 is taking away H(n)H(n) and giving the 1 back.

  13. the move: put the 1 next to the n - 1

    the line:
    E=(n−1)+1−H(n)E = (n - 1) + 1 - H(n)

    why it is allowed: Adding and taking away give the same in either order.

  14. the move: collect the ones

    the line:
    E=n−H(n)E = n - H(n)

    why it is allowed: (n−1)+1(n - 1) + 1 is nn. For 3 numbers, 3 less about 1.83 is about 1.17, line 8's 7 over 6. H(n)H(n) is more than 1 from 2 numbers on, so the average stays under n−1n - 1, the most swaps by the learn page's ladder on them.

try it on small rows: over every order of 3 numbers, the average EE is about 1.17

count it yourself

Follow every step on 4, 3, 2, 1, then check the comparisons against n(n−1)2\frac{n(n - 1)}{2}. Back to front it makes only 2 swaps, fewer than the 3 of 2, 4, 6, 1.

4, 3, 2, 1, every step written down
stepthe rowwhat happenscomparisonsswaps
14, 3, 2, 1There are 4 numbers in a row. Fill the places from the left, each with the smallest number not yet placed.4, 3, 2, 100
24, 3, 2, 1Start with 4, the number already in this place: it is the smallest so far.4, 3, 2, 100
34, 3, 2, 13 is smaller than 4.4, 3, 2, 110
44, 3, 2, 13 is the smallest so far now.4, 3, 2, 110
54, 3, 2, 12 is smaller than 3.4, 3, 2, 120
64, 3, 2, 12 is the smallest so far now.4, 3, 2, 120
74, 3, 2, 11 is smaller than 2.4, 3, 2, 130
84, 3, 2, 11 is the smallest so far now.4, 3, 2, 130
91, 3, 2, 4Swap 1 into the place, and 4 goes where 1 was.1, 3, 2, 431
101, 3, 2, 41 is in its place for good: nothing smaller is left.1, 3, 2, 431
111, 3, 2, 4Start with 3, the number already in this place: it is the smallest so far.1, 3, 2, 431
121, 3, 2, 42 is smaller than 3.1, 3, 2, 441
131, 3, 2, 42 is the smallest so far now.1, 3, 2, 441
141, 3, 2, 44 is not smaller than 2, so 2 is still the smallest so far.1, 3, 2, 451
151, 2, 3, 4Swap 2 into the place, and 3 goes where 2 was.1, 2, 3, 452
161, 2, 3, 42 is in its place for good: nothing smaller is left.1, 2, 3, 452
171, 2, 3, 4Start with 3, the number already in this place: it is the smallest so far.1, 2, 3, 452
181, 2, 3, 44 is not smaller than 3, so 3 is still the smallest so far.1, 2, 3, 462
191, 2, 3, 43 is the smallest left and already in this place, so no swap is needed. It stays there for good.1, 2, 3, 462
201, 2, 3, 4Only 4 is left, so it is in place too.1, 2, 3, 462
211, 2, 3, 4In order, after 6 comparisons and 2 swaps.1, 2, 3, 462

In all, 6 comparisons. The formula from section 4, n(n−1)2\frac{n(n - 1)}{2}, gives C=6C = 6 at n=4n = 4: the same.

where you meet it

Selection sort is rarely the fastest sort, but it suits rows where moving a number costs a lot, and its plan lives on in heap sort.

  • where moving a number costs far more than comparing two

    Selection sort makes at most n−1n - 1 swaps on any row. On 10 numbers back to front, counted on this site, bubble sort makes 45 swaps and insertion sort 45 moves, against its 5. So reach for it when each write, each change to what is stored, costs a lot and comparing is cheap. Large records that must be moved whole are one such case. Often a list saying where each record is kept is sorted instead, and the records are moved once, at the end. Selection sort earns its place when they must really move as they are sorted, and the list is short.

    source: Algorithmic Thinking Without the Jargon, volume one, chapter 8, and its answers appendix, answer 11.6

  • the plan inside heap sort

    The plan, fill each place with the smallest number left, works however the smallest is found. Heap sort keeps the numbers not yet placed in a heap, which hands over the one wanted without looking at every number. On this site heap sort fills the places from the right with the biggest left.

    source: Algorithmic Thinking Without the Jargon, volume one, chapter 8, and volume two, chapter 24; this site's heap sort watch page

what is used instead

On long rows the comparisons are far too many: a million numbers take about 500 billion, in order or not. Merge sort makes far fewer on every row, and quick sort on a shuffled one, each on its own page. On a short row nearly in order, insertion sort costs far less, since each number it places stops early.

how it compares

Selection sort beside the other ways to put a row in order, on one plot and in one table. Its line runs just above bubble sort's. Insertion sort's runs a little below both: about half as many comparisons, a small gap on a scale where each mark is ten times the last. At 1,000 shuffled numbers the three make about 499,500, 498,500 and 250,000. In the table, bubble sort's line speaks of a walk and insertion sort's of a slide, their words for one trip along the row.

comparisons on a shuffled row, on the log-log scales of section 2, one line for each way whose page is written
102104106108101010121014101102103104105106107bubble sortcocktail shaker sortinsertion sortshell sortquick sortrandomised quick sortmerge sortheap sortselection sort10110210310410510610710810910101011101210131014101102103104105106107bubble sortcocktail shaker sortinsertion sortshell sortquick sortrandomised quick sortmerge sortheap sortselection sort
  • bubble sort
  • cocktail shaker sort
  • insertion sort
  • selection sort
  • shell sort
  • quick sort
  • randomised quick sort
  • merge sort
  • heap sort
put a row in order: each way side by side
waybestaverageworstextra memorykeeps equal items in orderworks in placereach for it when
bubble sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)a few spare places (the walk number, the pair's place, whether the walk swapped, room for a number while two swap), the same however long the rowyesyesyou are learning how sorting works; for real work, insertion sort, which on every order of up to 8 different numbers makes no more comparisons, counted order by order
cocktail shaker sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)a few spare places, the same however long the rowyesyesyou are learning how sorting works; for real work, insertion sort
insertion sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)room for a few numbers (the number being placed, where its slide has reached, which number is next), the same however long the rowyesyesthe row is short, a few dozen numbers, or nearly in order
selection sortΘ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)room for a few numbers (the place being filled, where the smallest so far stands, the number looked at, one held during a swap), the same however long the rownoyesmoving a number costs far more than comparing two, and the row is short
shell sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)not known; between Ω(n log⁡2 n)\Omega(n \,\log_2\, n) and O(n2)O(n^2)not worked out here; between Ω(n log⁡2 n)\Omega(n \,\log_2\, n) and O(n2)O(n^2)a few spare places (the gap, the number picked up, its place), the same however long the rownoyesyou want a few lines of code and no room beyond the row. On this site's shuffles of 200 to 10,000 numbers it averaged under a fifth of insertion sort's comparisons
quick sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2)a list of the parts still to sort, two memory places each. That is two places for each number on a row in order, and far fewer on a shuffle, about 51 for 100,000 numbers. So this plain version does not work in place, as its spare room grows with the rownonoyou want a fast sort on shuffled rows with no second row, and equal items need not keep their order; use a version with a random or middle pivot
randomised quick sortat most O(n log⁡2 n)O(n \,\log_2\, n), as every row of different numbers averages that over the picks; a row with equal numbers can cost a little lessΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2), a row of equal numbers, whatever the picks; no run costs more, since a pair meets at most oncea list of the parts waiting to be sorted, each kept as its first and last place. On average far shorter than the row, about 66 places for a million numbers. Unlucky picks can make it grow with the rownonoyou want quick sort without a dear row in order, and equal items need not keep their order
merge sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)a second row as long as the rowyesnoyou need comparisons growing no faster than n log⁡2 nn \,\log_2\, n on every row, equal items kept in order, or a file too big for memory sorted
heap sortΘ(n)\Theta(n), every number the sameΘ(n log⁡2 n)\Theta(n \,\log_2\, n), shuffled; measured, no formula worked out hereΘ(n log⁡2 n)\Theta(n \,\log_2\, n), the dearest row; this page finds it only for short rows, by trying every ordera few places, however long the rownoyesyou need a sort with no slow row and no second row, and equal items need not keep their order
counting sortΘ(n)\Theta(n) steps, every row alikeΘ(n)\Theta(n) stepsΘ(n)\Theta(n) steps, every row alikea second row of n places and 10 talliesyesnothe numbers are small whole numbers, such as ratings from 0 to 9, and equal ones must keep their order
radix sortΘ(n)\Theta(n) placings, every number below 10Θ(n)\Theta(n) placings, between the best and the worst, as every order costs the sameΘ(n)\Theta(n) placings, three passes for numbers up to 999a second row of n places and 10 talliesyesnomany whole numbers with few digits, such as numbers from 0 to 999
extra memory:
the room it needs on top of the input itself, while it runs.
keeps equal items in order:
people sorted by age keep the order they arrived in within each age; in general, two items equal in what is being sorted come out in the order they went in.
works in place:
it rearranges the input where it stands, with only a few spare places, rather than building a copy; a different sense from a number being in place, in its final position.

race them on one row of your own