Selection sort
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 at | smallest so far |
|---|---|
| 5, the start | 5 |
| 8 | 5 |
| 3 | 3 |
| 9 | 3 |
| 4 | 3 |
| the row | 42, 7, 31, 18, 56, 23, 12, 49 |
|---|---|
| after pass 1 | 7, 42, 31, 18, 56, 23, 12, 49 |
| after pass 2 | 7, 12, 31, 18, 56, 23, 42, 49 |
| after pass 3 | 7, 12, 18, 31, 56, 23, 42, 49 |
| after pass 4 | 7, 12, 18, 23, 56, 31, 42, 49 |
| after pass 5 | 7, 12, 18, 23, 31, 56, 42, 49 |
| after pass 6 | 7, 12, 18, 23, 31, 42, 56, 49 |
| after pass 7 | 7, 12, 18, 23, 31, 42, 49, 56 |
step 2 of 61
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.
step 4 of 61
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
step 11 of 61
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.
step 12 of 61
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.
step 21 of 61
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
step 24 of 61
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.
step 48 of 61
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.
step 61 of 61
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.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- for each place from the left, all but the lastPython line 9
- the smallest so far is the number in that placePython line 10
- look at each number after itPython line 11
- if it is smaller, it is the smallest so farPython lines 12 and 13
- 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 numbers makes the same comparisons, , 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
, 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
| comparisons | time | |
|---|---|---|
| 1,000 | 499,500 | about 500 microseconds |
| 100,000 | 4,999,950,000 | about 5 seconds |
| 10,000,000 | 49,999,995,000,000 | about 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.
| bestalready in order, the only kind of row with no swap | averageshuffled, different numbers in a random order, every order as likely | worstdifferent numbers in order but for the smallest, moved last, such as 2, 4, 6, 8, 1, a row where every pass swaps | |
|---|---|---|---|
| comparisons | |||
| swaps | none | ||
| how the comparisons grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
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 5 | comparisons | swaps |
|---|---|---|
| 1, 2, 3, 4, 5 | 10 | 0 |
| 5, 4, 3, 2, 1 | 10 | 2 |
| 2, 4, 6, 8, 1 | 10 | 4 |
| all 120 orders, on average | 10 | about 2.72 |
| the row | 5, 4, 3, 2, 1 |
|---|---|
| after swap 1 | 1, 4, 3, 2, 5 |
| after swap 2 | 1, 2, 3, 4, 5 |
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.
the move: count one pass
the line:why it is allowed: Each of the numbers after place is compared once. On 5, 8, 3, 9, 4, pass 2 compares 3 numbers, 5 less 2. Their order never changes how many.
the move: count the passes
the line:why it is allowed: Once places 1 to hold the smallest numbers, the one left is the biggest, already at place .
guess it, thenthe move: add up the passes
the line:why it is allowed: is the comparisons on any row of numbers, line 1 added over line 2's passes. For 4 numbers, 3 + 2 + 1.
guess it, thenthe move: add them the other way round
the line:why it is allowed: The same numbers in the other order. For 4 numbers, 1 + 2 + 3 is 3 + 2 + 1, 6.
guess it, thenthe move: use the page on adding up, for a sum that stops at n - 1
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line: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 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 , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: Line 4's sum ends at . 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.
guess it, thenthe move: tidy the bracket
the line:why it is allowed: One more than is .
guess it, thenthe move: write the product the other way round
the line:why it is allowed: The same product.
guess it, thenthe move: multiply out the bracket
the line:why it is allowed: lots of make , and lots of 1 make . For 4 numbers, 4 times 3 is 12, which is 16 less 4.
guess it, thenthe move: halve each part
the line:why it is allowed: Half of a difference is the difference of the halves.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 9 takes something away from . For 4 numbers, 6 is at most 8, half of 16.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 10, stays under a fixed multiple of , a half.
guess it, thenthe move: a fact about n
the line:why it is allowed: Now a floor. is times half of , and half of is at least 1 from 2 numbers on. For 10 numbers, 10 is at most 50.
guess it, thenthe move: a fact for the floor, halving both sides
the line:2 1 1 4 2 4 10 5 25 100 50 2,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 alone.
guess it, thenthe move: a floor
the line:why it is allowed: For 10 numbers, 45 is at least 50 less 25. Line 9 takes away ; line 13's is at least that, and taking away more leaves less.
guess it, thenthe move: tidy the floor
the line:why it is allowed: Half less a quarter is a quarter.
guess it, thenthe move: read it as a bound
the line:floor, ceiling, 2 1 1 2 4 4 6 8 10 25 45 50 100 2,500 4,950 5,000 From 2 numbers on, sits between a quarter and a half of . That squeeze is . why it is allowed: By line 15, stays at or above a fixed multiple of , a quarter, from 2 numbers on. A floor need only hold for rows long enough; at 1 number is 0.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 16 and 11 bound by the same growth, .
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: every pass still looks at every number left
the line:pass looks at comparisons swap 1 2, 3, 4, 5 4 no 2 3, 4, 5 3 no 3 4, 5 2 no 4 5 1 no 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 is already the smallest left, but the pass learns that only by comparing it with all numbers after it.
the move: add up the passes
the line:why it is allowed: is the comparisons on a row in order, line 1 added over the first ladder's passes. For 4 numbers, 3 + 2 + 1.
guess it, thenthe move: add them the other way round
the line:why it is allowed: The same numbers in the other order.
guess it, thenthe move: use the page on adding up, for a sum that stops at n - 1
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line: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 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 , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: As in the first ladder's line 5.
guess it, thenthe move: tidy the bracket
the line:why it is allowed: One more than is .
guess it, thenthe move: write the product the other way round
the line: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 .
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: every shuffle costs the same
the line:shuffle comparisons 1, 2, 3 3 1, 3, 2 3 2, 1, 3 3 2, 3, 1 3 3, 1, 2 3 3, 2, 1 3 in all 18 average 3 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 numbers makes the same sum, whatever its order.
the move: average a count that never changes
the line:why it is allowed: is the comparisons averaged over every shuffle of 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.
guess it, thenthe move: add them the other way round
the line:why it is allowed: The same numbers in the other order.
guess it, thenthe move: use the page on adding up, for a sum that stops at n - 1
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line: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 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 , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: As in the first ladder's line 5.
guess it, thenthe move: tidy the bracket
the line:why it is allowed: One more than is .
guess it, thenthe move: write the product the other way round
the line: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 .
guess it, then
try it on small rows: over every order of 4 numbers, the average is
the move: each pass finds its smallest at home
the line: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.
the move: count the swaps
the line:why it is allowed: is the swaps on a row in order. A pass swaps only when its smallest is away from home, which line 1 rules out.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: one swap at most per pass
the line:why it is allowed: A pass ends with one swap of its smallest into its place, or none when it is already home.
the move: no row makes more
the line:why it is allowed: The first ladder's line 2 counts passes, and by line 1 each swaps at most once. For 4 numbers, 3.
guess it, thenthe move: on 2, 3, ..., n, 1, every pass swaps
the line:the row 2, 4, 6, 1 after pass 1 1, 4, 6, 2 after pass 2 1, 2, 6, 4 after pass 3 1, 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.
guess it, thenthe move: count the swaps
the line:most swaps comparisons 10 9 45 100 99 4,950 1,000 999 499,500 Ten times the numbers makes about ten times the most swaps, but about a hundred times the comparisons. why it is allowed: is the swaps on that row, one for each of the passes by line 3, the most line 2 allows. For 4 numbers, 3.
guess it, thenthe move: a ceiling
the line:why it is allowed: One less than is less than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, stays under a fixed multiple of , 1 times.
guess it, thenthe move: a fact for the floor
the line:why it is allowed: Half of is at least 1 from 2 numbers on. For 10 numbers, 1 is at most 5.
guess it, thenthe move: a floor
the line:why it is allowed: Line 4 takes away 1, at most line 7's , and taking away more leaves less. For 10 numbers, 9 is at least 10 less 5.
guess it, thenthe move: tidy the floor
the line:why it is allowed: less half of is half of . For 10 numbers, 9 is at least 5.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 9, from 2 numbers on.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 10 and 6 bound by the same growth, , while by the first ladder the comparisons grow like .
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: when a pass swaps
the line: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 to , which is places. Places 2 to 5 are 4 places, 5 less 2, plus 1.
the move: what is left is still a shuffle
the line:shuffle the 1 at place after pass 1 places 2 and 3 1, 2, 3 1 1, 2, 3 2, 3 2, 1, 3 2 1, 2, 3 2, 3 3, 2, 1 3 1, 2, 3 2, 3 1, 3, 2 1 1, 3, 2 3, 2 3, 1, 2 2 1, 3, 2 3, 2 2, 3, 1 3 1, 3, 2 3, 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, 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.
guess it, thenthe move: the chance of no swap
the line: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 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 , the first, in 1 of every orders. In the picture the 1 is at each place in 2 of the 6 shuffles, a third.
guess it, thenthe move: the swaps are a sum of tallies
the line: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.
guess it, thenthe move: average tally by tally
the line:shuffle pass 1 pass 2 swaps 1, 2, 3 0 0 0 1, 3, 2 0 1 1 2, 1, 3 1 0 1 2, 3, 1 1 1 2 3, 1, 2 1 1 2 3, 2, 1 1 0 1 in all 4 3 7 average 4 over 6 3 over 6 7 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.
guess it, thenthe move: a tally's average is its chance
the line: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.
guess it, thenthe move: a swap or none
the line: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.
guess it, thenthe move: add up the passes
the line:why it is allowed: is the swaps averaged over every shuffle of different numbers. By lines 5 to 7, place 1 adds , down to for place . For 3 numbers, two thirds plus a half, 7 over 6.
guess it, thenthe move: take the ones out
the line:why it is allowed: brackets, each 1 less a fraction. The ones make , and every fraction is taken away.
guess it, thenthe move: add the fractions the other way round
the line:why it is allowed: The same fractions in the other order.
guess it, thenthe move: name the sum
the line:why it is allowed: 1, plus a half, and on up to 1 over , is the harmonic sum, . This sum lacks its first 1.
guess it, thenthe move: open the bracket
the line:why it is allowed: Taking away less 1 is taking away and giving the 1 back.
guess it, thenthe move: put the 1 next to the n - 1
the line:why it is allowed: Adding and taking away give the same in either order.
guess it, thenthe move: collect the ones
the line:why it is allowed: is . For 3 numbers, 3 less about 1.83 is about 1.17, line 8's 7 over 6. is more than 1 from 2 numbers on, so the average stays under , the most swaps by the learn page's ladder on them.
guess it, then
try it on small rows: over every order of 3 numbers, the average is about 1.17
count it yourself
Follow every step on 4, 3, 2, 1, then check the comparisons against . Back to front it makes only 2 swaps, fewer than the 3 of 2, 4, 6, 1.
| step | the row | what happens | comparisons | swaps |
|---|---|---|---|---|
| 1 | 4, 3, 2, 1 | There are 4 numbers in a row. Fill the places from the left, each with the smallest number not yet placed.4, 3, 2, 1 | 0 | 0 |
| 2 | 4, 3, 2, 1 | Start with 4, the number already in this place: it is the smallest so far.4, 3, 2, 1 | 0 | 0 |
| 3 | 4, 3, 2, 1 | 3 is smaller than 4.4, 3, 2, 1 | 1 | 0 |
| 4 | 4, 3, 2, 1 | 3 is the smallest so far now.4, 3, 2, 1 | 1 | 0 |
| 5 | 4, 3, 2, 1 | 2 is smaller than 3.4, 3, 2, 1 | 2 | 0 |
| 6 | 4, 3, 2, 1 | 2 is the smallest so far now.4, 3, 2, 1 | 2 | 0 |
| 7 | 4, 3, 2, 1 | 1 is smaller than 2.4, 3, 2, 1 | 3 | 0 |
| 8 | 4, 3, 2, 1 | 1 is the smallest so far now.4, 3, 2, 1 | 3 | 0 |
| 9 | 1, 3, 2, 4 | Swap 1 into the place, and 4 goes where 1 was.1, 3, 2, 4 | 3 | 1 |
| 10 | 1, 3, 2, 4 | 1 is in its place for good: nothing smaller is left.1, 3, 2, 4 | 3 | 1 |
| 11 | 1, 3, 2, 4 | Start with 3, the number already in this place: it is the smallest so far.1, 3, 2, 4 | 3 | 1 |
| 12 | 1, 3, 2, 4 | 2 is smaller than 3.1, 3, 2, 4 | 4 | 1 |
| 13 | 1, 3, 2, 4 | 2 is the smallest so far now.1, 3, 2, 4 | 4 | 1 |
| 14 | 1, 3, 2, 4 | 4 is not smaller than 2, so 2 is still the smallest so far.1, 3, 2, 4 | 5 | 1 |
| 15 | 1, 2, 3, 4 | Swap 2 into the place, and 3 goes where 2 was.1, 2, 3, 4 | 5 | 2 |
| 16 | 1, 2, 3, 4 | 2 is in its place for good: nothing smaller is left.1, 2, 3, 4 | 5 | 2 |
| 17 | 1, 2, 3, 4 | Start with 3, the number already in this place: it is the smallest so far.1, 2, 3, 4 | 5 | 2 |
| 18 | 1, 2, 3, 4 | 4 is not smaller than 3, so 3 is still the smallest so far.1, 2, 3, 4 | 6 | 2 |
| 19 | 1, 2, 3, 4 | 3 is the smallest left and already in this place, so no swap is needed. It stays there for good.1, 2, 3, 4 | 6 | 2 |
| 20 | 1, 2, 3, 4 | Only 4 is left, so it is in place too.1, 2, 3, 4 | 6 | 2 |
| 21 | 1, 2, 3, 4 | In order, after 6 comparisons and 2 swaps.1, 2, 3, 4 | 6 | 2 |
In all, 6 comparisons. The formula from section 4, , gives at : 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 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.
- bubble sort
- cocktail shaker sort
- insertion sort
- selection sort
- shell sort
- quick sort
- randomised quick sort
- merge sort
- heap sort
| way | best | average | worst | extra memory | keeps equal items in order | works in place | reach for it when |
|---|---|---|---|---|---|---|---|
| bubble sort | 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 row | yes | yes | you 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 | a few spare places, the same however long the row | yes | yes | you are learning how sorting works; for real work, insertion sort | |||
| insertion sort | room for a few numbers (the number being placed, where its slide has reached, which number is next), the same however long the row | yes | yes | the row is short, a few dozen numbers, or nearly in order | |||
| selection sort | 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 | no | yes | moving a number costs far more than comparing two, and the row is short | |||
| shell sort | not known; between and | not worked out here; between and | a few spare places (the gap, the number picked up, its place), the same however long the row | no | yes | you 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 | 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 row | no | no | you 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 sort | at most , as every row of different numbers averages that over the picks; a row with equal numbers can cost a little less | , a row of equal numbers, whatever the picks; no run costs more, since a pair meets at most once | a 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 row | no | no | you want quick sort without a dear row in order, and equal items need not keep their order | |
| merge sort | a second row as long as the row | yes | no | you need comparisons growing no faster than on every row, equal items kept in order, or a file too big for memory sorted | |||
| heap sort | , every number the same | , shuffled; measured, no formula worked out here | , the dearest row; this page finds it only for short rows, by trying every order | a few places, however long the row | no | yes | you need a sort with no slow row and no second row, and equal items need not keep their order |
| counting sort | steps, every row alike | steps | steps, every row alike | a second row of n places and 10 tallies | yes | no | the numbers are small whole numbers, such as ratings from 0 to 9, and equal ones must keep their order |
| radix sort | placings, every number below 10 | placings, between the best and the worst, as every order costs the same | placings, three passes for numbers up to 999 | a second row of n places and 10 tallies | yes | no | many 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.