Insertion sort
how it works
The idea in a few sentences and two pictures, then one row sorted step by step.
Insertion sort puts a row of numbers in order, smallest first. The numbers on the left are kept in order, starting with the first on its own. Pick up the next number and slide it left. While the number on its left is bigger, the two trade places: one move. The slide stops at a number that is not bigger, or at the front. A number slides past exactly the bigger numbers before it, so a row nearly in order costs little. Equal numbers never pass each other.
| the row | 15, 35, 45, 25 |
|---|---|
| after move 1 | 15, 35, 25, 45 |
| after move 2 | 15, 25, 35, 45 |
| the row | 42, 7, 31, 18, 56, 23, 12, 49 |
|---|---|
| after slide 1 | 7, 42, 31, 18, 56, 23, 12, 49 |
| after slide 2 | 7, 31, 42, 18, 56, 23, 12, 49 |
| after slide 3 | 7, 18, 31, 42, 56, 23, 12, 49 |
| after slide 4 | 7, 18, 31, 42, 56, 23, 12, 49 |
| after slide 5 | 7, 18, 23, 31, 42, 56, 12, 49 |
| after slide 6 | 7, 12, 18, 23, 31, 42, 56, 49 |
| after slide 7 | 7, 12, 18, 23, 31, 42, 49, 56 |
step 2 of 49
Pick up 7 and carry it left past every bigger number before it.
what it remembers to know where it is
- number being placed
- 7
- its place now
- 2
step 5 of 49
7 has reached the front: there is nothing left of it to compare with.
what it remembers to know where it is
- number being placed
- 7
- its place now
- 1
step 10 of 49
7 is not bigger than 31, so 31 belongs just after it.
what it remembers to know where it is
- number being placed
- 31
- its place now
- 2
step 20 of 49
42 is not bigger than 56, so 56 belongs just after it.
what it remembers to know where it is
- number being placed
- 56
- its place now
- 5
step 31 of 49
Pick up 12 and carry it left past every bigger number before it.
what it remembers to know where it is
- number being placed
- 12
- its place now
- 7
step 42 of 49
7 is not bigger than 12, so 12 belongs just after it.
what it remembers to know where it is
- number being placed
- 12
- its place now
- 2
step 48 of 49
49 is in its place among the numbers picked up so far, so the first 8 numbers are in order.
what it remembers to know where it is
- number being placed
- 49
- its place now
- 7
step 49 of 49
In order, after 19 comparisons and 13 moves.
what it remembers to know where it is
- number being placed
- not yet
- its place now
- 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 number from the second to the lastPython line 10
- take it out of the rowPython lines 11 and 12
- while the number on its left is biggerPython line 13
- move that number one place rightPython lines 14 and 15
- put the number taken out in the gapPython line 16
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 insertion_sort(numbers):
"""Put a list of numbers in order, smallest first, in the list itself.
Take each number in turn, from the second to the last, and move every
bigger number before it one place right, until the one on its left is
not bigger or it reaches the front; then put it in the gap. The part on
the left is always in order. The list is sorted where it stands, with no
copy made, and handed back.
"""
for i in range(1, len(numbers)): # i runs through 1, 2, and so on to the last place
placing = numbers[i] # take it out of the list
gap = i # the place it leaves empty
while gap > 0 and numbers[gap - 1] > placing:
numbers[gap] = numbers[gap - 1] # move the bigger number one place right
gap -= 1 # the gap moves one place left
numbers[gap] = placing # put it in the gap
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. A row in order climbs one step up for each step across. A row back to front climbs two: ten times the numbers, about a hundred times the comparisons. Section 4 shows why. A shuffled row climbs like a row back to front, a little lower. Its points are the mean of 20 shuffles at each length, within 5 in a hundred of section 4's exact average.
comparisons, ten times more at each mark up
, how many numbers are in the row, ten times more at each mark to the right
- back to front, one of the dearest rowssolid 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, one of the cheapest rowssolid 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 insertion 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 a row back to front, and the average over 20
shuffles. 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 __gt__(self, other):
Counted.comparisons += 1
return self.value > other.value
def insertion_sort(numbers):
"""Put a list of numbers in order, smallest first, in the list itself.
Take each number in turn, from the second to the last, and move every
bigger number before it one place right, until the one on its left is
not bigger or it reaches the front; then put it in the gap. The part on
the left is always in order. The list is sorted where it stands, with no
copy made, and handed back.
"""
for i in range(1, len(numbers)): # i runs through 1, 2, and so on to the last place
placing = numbers[i] # take it out of the list
gap = i # the place it leaves empty
while gap > 0 and numbers[gap - 1] > placing:
numbers[gap] = numbers[gap - 1] # move the bigger number one place right
gap -= 1 # the gap moves one place left
numbers[gap] = placing # put it in the gap
return numbers
def count(row):
"""How many comparisons insertion sort makes on this row."""
Counted.comparisons = 0
insertion_sort([Counted(x) for x in row])
return Counted.comparisons
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>6} {'in order':>10} {'back to front':>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)))
back_to_front = count(list(range(n, 0, -1)))
print(f"{n:>6} {in_order:>10} {back_to_front:>14} {sum(shuffles) / 20:>10.1f}")
best, worst and average
The same slides cost little or much, depending on the row. Other rows can tie with the cheapest and the dearest.
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, one of the cheapest rows | averageshuffled, different numbers in a random order, every order as likely | worstback to front, one of the dearest rows | |
|---|---|---|---|
| comparisons | |||
| moves | none | ||
| how the comparisons grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: room for a few numbers (the number being placed, where its slide has reached, which number is next), 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 | moves |
|---|---|---|
| 1, 2, 3, 4, 5 | 4 | 0 |
| all 120 orders, on average | about 7.72 | 5 |
| 5, 4, 3, 2, 1 | 10 | 10 |
| row | comparisons by each number placed | in all |
|---|---|---|
| 1, 2, 3, 4 | 1, 1, 1 | 3 |
| 2, 1, 3, 4 | 1, 1, 1 | 3 |
| 4, 3, 2, 1 | 1, 2, 3 | 6 |
| 1, 4, 3, 2 | 1, 2, 3 | 6 |
where the formula comes from
Each count above, worked out in small steps. Every step names the line it uses.
the move: count what one number can cost
the line:why it is allowed: numbers stand before it, and each comparison looks one place further left, so it meets each at most once. The 12 of section 1, at place 7, makes 6.
the move: no row costs more
the line:why it is allowed: By line 1, places 2 to cost at most 1, 2, and on up to . For 4 numbers, 1 + 2 + 3.
guess it, thenthe move: see the slides on a row back to front
the line:the row 4, 3, 2, 1 after slide 1 3, 4, 2, 1 after slide 2 2, 3, 4, 1 after slide 3 1, 2, 3, 4 Each slide passes every number before it, to the front. why it is allowed: Each number is smaller than all before it, and the slides so far only reorder those. So every comparison finds a bigger number, until the front.
guess it, thenthe move: so each costs its most
the line:why it is allowed: By line 3 it meets all , the most line 1 allows. On 4, 3, 2, 1 the 3, the 2 and the 1 make 1, 2 and 3.
guess it, thenthe move: add up the comparisons of the numbers placed
the line:why it is allowed: is the comparisons on a row back to front, line 4 added over places 2 to .
guess it, thenthe move: so this row is one of the dearest
the line:why it is allowed: By lines 2 and 5.
guess it, thenthe move: use the page on adding up, reading its n as 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 5'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 .
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 11 takes something away from .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 12, stays under a fixed multiple of , a half.
guess it, thenthe move: a fact for the floor
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: At 10 numbers line 11 is 50 less 5. Swapping the 5 for 25, a quarter of 10 squared, leaves 25, still under 45 and made of alone. Times 4, this line says twice is at most times , true from 2 numbers on.
guess it, thenthe move: a floor
the line:why it is allowed: Line 11 takes away , at most line 14's , and taking away more leaves less. For 10 numbers, 45 is at least 50 less 25.
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:why it is allowed: By line 16, stays 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 17 and 13 bound by the same growth, .
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
the move: no row costs less
the line:why it is allowed: Each number from place 2 on has a left neighbour, so its slide starts with a comparison.
the move: on a row in order, one comparison each
the line:placing compared with a move 2 1 no 3 2 no 4 3 no 5 4 no On 1, 2, 3, 4, 5: 4 comparisons, which is 5 less 1, and no move. why it is allowed: is now the comparisons on a row in order. Each first comparison finds a number not bigger and stops the slide.
guess it, thenthe move: so this row is a cheapest one
the line:why it is allowed: By lines 1 and 2.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 2 takes 1 from , which leaves less than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 4.
guess it, thenthe move: a fact for the floor
the line:why it is allowed: Half of is at least 1 once is 2 or more.
guess it, thenthe move: a floor
the line:why it is allowed: Line 2 takes away 1, at most line 6'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 .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8, from 2 numbers on.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 9 and 5 bound by the same growth, .
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: see what one move does
the line:why it is allowed: The bigger number steps right as the number being placed steps left. In 3, 8, 5, placing the 5 moves the 8, giving 3, 5, 8.
the move: a move mends one inversion
the line:pair in 4, 9, 7, 2 in 4, 7, 9, 2 4 and 9 right right 4 and 7 right right 4 and 2 wrong wrong 9 and 7 wrong right 9 and 2 wrong wrong 7 and 2 wrong wrong Every pair, before and after the move of the 9 and the 7. Only that pair changes. why it is allowed: The two stand the wrong way round, and the move turns them. Every other number stands left of both or right of both, before and after, so no other pair changes.
guess it, thenthe move: count the moves as inversions
the line:why it is allowed: By line 2, and the sorted row has none left. 4, 9, 7, 2 has 4 inversions and takes 4 moves.
guess it, thenthe move: count the pairs
the line:why it is allowed: A pair is any two numbers. Count each at its second number, place 2 pairing with 1 number, place 3 with 2, up to place with . For 4 numbers, 1 + 2 + 3.
guess it, thenthe move: each pair is wrong half the time
the line:pair 1 and 2 wrong traded, now right 2, 1, 3 1, 2, 3 2, 3, 1 1, 3, 2 3, 2, 1 3, 1, 2 The 1 and the 2 traded. 3 of the 6 shuffles have that pair wrong, and 3 right. why it is allowed: The numbers are all different. Trading a pair's two numbers turns a shuffle with it wrong into one with it right, and back.
guess it, thenthe move: count the wrong pairs two ways
the line:shuffle 1 and 2 1 and 3 2 and 3 wrong pairs 1, 2, 3 0 1, 3, 2 x 1 2, 1, 3 x 1 2, 3, 1 x x 2 3, 1, 2 x x 2 3, 2, 1 x x x 3 in all 3 3 3 9 The 6 shuffles of 1, 2 and 3, an x where a pair stands wrong. why it is allowed: Mark an x where a pair is wrong. Adding along the rows or down the columns counts each mark once, so both give 9.
guess it, thenthe move: add up the wrong pairs pair by pair
the line:why it is allowed: Each column counts the shuffles with its pair wrong, half of them by line 5. For 3 numbers, 3 pairs times 3 is 9.
guess it, thenthe move: divide by the shuffles
the line:why it is allowed: Line 7's total over the number of shuffles. For 3 numbers, 9 over 6 is 1.5.
guess it, thenthe move: the average moves are the average wrong pairs
the line:why it is allowed: By line 3 each shuffle's moves are its wrong pairs, so their averages match, line 8's.
guess it, thenthe move: put in the count of pairs
the line:why it is allowed: is the moves averaged over every shuffle of different numbers. By line 9, half the pairs of line 4.
guess it, thenthe move: use the page on adding up, reading its n as 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 7. For 3 numbers, 2 times 3, halved, is 3.
guess it, thenthe move: tidy the bracket
the line:why it is allowed: One more than is .
guess it, thenthe move: multiply the fractions
the line:why it is allowed: Half of a half is a quarter. For 3 numbers, 2 times 3 over 4 is 1.5, as in line 8.
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 .
guess it, thenthe move: take a quarter of each part
the line:why it is allowed: A quarter of a difference is the difference of the quarters.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 16 takes something away from .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 17.
guess it, thenthe move: a fact for the floor
the line:2 0.5 0.5 4 1 2 10 2.5 12.5 100 25 1,250 Equal at 2 numbers, then the eighth of n squared pulls ever further ahead. why it is allowed: Times 8, this says twice is at most times , as at the first ladder's line 14.
guess it, thenthe move: a floor
the line:why it is allowed: Line 16 takes away , at most line 19's , and taking away more leaves less. For 10 numbers, 22.5 is at least 25 less 12.5.
guess it, thenthe move: tidy the floor
the line:why it is allowed: A quarter less an eighth is an eighth.
guess it, thenthe move: read it as a bound
the line:- the average moves,
- the ceiling of line 17,
- the floor of line 21,
Log-log, from 10 to ten million numbers. The average moves run between the ceiling and the floor, which stay the same distance apart, the ceiling always twice the floor. why it is allowed: By line 21, from 2 numbers on.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 22 and 18 bound by the same growth, .
guess it, then
try it on small rows: over every order of 3 numbers, the average is
the move: count one number's comparisons
the line:why it is allowed: A comparison that finds a bigger number is followed by its move. The slide ends at a number not bigger, one more comparison, or at the front, none.
the move: add over the numbers placed
the line:shuffle moves reach the front comparisons 1, 2, 3 0 0 2 1, 3, 2 1 0 3 2, 1, 3 1 1 2 2, 3, 1 2 1 3 3, 1, 2 2 1 3 3, 2, 1 3 2 3 in all 9 5 16 Each shuffle of 1, 2 and 3. Its moves, plus 2, less those that reach the front, make its comparisons. why it is allowed: Line 1, added over the numbers placed. On 2, 5, 1, 4, 3: 5 moves, plus 4, less 1 for the 1, make 8.
guess it, thenthe move: see which numbers reach the front
the line:the shuffle 3, 1, 4, 2 after slide 1 1, 3, 4, 2 after slide 2 1, 3, 4, 2 after slide 3 1, 2, 3, 4 After slide 2, places 1 to 3 hold 1, 3 and 4, the shuffle's first three numbers. The 2 reaches the front only if all three are bigger. Here the 1 is not, so the 2 stops after it. why it is allowed: When a number is picked up, the numbers before it are the ones the shuffle put there, now in order. Its slide passes the bigger ones, so it reaches the front only if all are bigger.
guess it, thenthe move: each place is as likely
the line:Each arrow trades the two places underlined in red, pairing up the shuffles as they stand before sorting. For 3 numbers, each place holds the 1 in 2 of the 6 shuffles. why it is allowed: This line is about the row before any sorting. Trading two of the first places keeps the same numbers there, so their smallest is the same number, now at the other place. In 2, 3, 1, trading places 1 and 3 gives 1, 3, 2, the picture's first arrow. Trading back undoes it, so each shuffle with the smallest at one place pairs with one with it at the other. So any two of the first places hold it equally often, and so do all .
guess it, thenthe move: the chance at place k
the line:shuffle place 2 place 3 1, 2, 3 0 0 1, 3, 2 0 0 2, 1, 3 1 0 2, 3, 1 0 1 3, 1, 2 1 0 3, 2, 1 1 1 in all 3 2 average 1 over 2 1 over 3 A 1 where the number at that place is a new smallest, a 0 where not. why it is allowed: By line 3 it must be the smallest of the first . That smallest stands at one place in each shuffle, and by line 4 at each place equally often, so at place in 1 of every . In the picture, place 2 holds a new smallest in 3 of the 6, a half, and place 3 in 2, a third.
guess it, thenthe move: average the three pieces
the line:why it is allowed: Each average divides a total by the same number of shuffles, and adding totals then dividing gives what dividing then adding gives. So the average of a sum is the sum of the averages, and the averages to itself. For 3 numbers, line 2's 9 moves, plus 2 times 6, less 5, make 16 over 6 shuffles.
guess it, thenthe move: the count is a sum of tallies
the line:why it is allowed: By line 3, a place's tally is 1 when it holds a new smallest, and 0 when not. On 3, 2, 1 both tallies are 1, and 2 numbers reach the front.
guess it, thenthe move: average tally by tally
the line:why it is allowed: Line 6's rule, for a sum of tallies.
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, which line 5 finds is 1 over .
guess it, thenthe move: count those that reach the front
the line:why it is allowed: Line 9 put into line 8. For 3 numbers, a half and a third make 5 over 6, as line 2's 5 over its 6 shuffles.
guess it, thenthe move: put the pieces together
the line:why it is allowed: is the comparisons averaged over every shuffle of different numbers. Into line 6 go the ladder before's average moves and line 10's count.
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, 1.5 plus 3 less about 1.83 is about 2.67, as line 2's 16 over 6.
guess it, thenthe move: a floor from the moves
the line:why it is allowed: Every move follows a comparison, so is at least the ladder before's average moves.
guess it, thenthe move: a simpler floor
the line:why it is allowed: By the ladder before, lines 14 to 21.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 17, from 2 numbers on.
guess it, thenthe move: a ceiling from the dearest rows
the line:numbers floor, line 16 the average ceiling, line 19 3 1.5 about 2.67 3 5 5 about 7.72 10 8 14 about 19.28 28 The comparisons averaged over every order, counted on this site's insertion sort. why it is allowed: By the first ladder no row costs more, so neither does the average. In the picture, by 8 numbers the average sits nearer the floor.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: By the first ladder's lines 11 and 12.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 20.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 18 and 21 bound by the same growth, . For 1,000 numbers is about 7.5, beside about 250,000 from the moves.
guess it, then
try it on small rows: over every order of 3 numbers, the average is about 2.67
the move: every pair is wrong
the line:why it is allowed: Each number is smaller than every number before it. All 6 pairs of 4, 3, 2, 1 are wrong.
the move: the moves are the inversions
the line:why it is allowed: Line 3 of the ladder on average moves.
guess it, thenthe move: one move for each pair
the line:the row 4, 3, 2, 1 after move 1 3, 4, 2, 1 after move 2 3, 2, 4, 1 after move 3 2, 3, 4, 1 after move 4 2, 3, 1, 4 after move 5 2, 1, 3, 4 after move 6 1, 2, 3, 4 6 moves, one for each of the 6 pairs. why it is allowed: By lines 1 and 2.
guess it, thenthe move: put in the count of pairs
the line:why it is allowed: is this row's moves. By line 3 they are its pairs, which line 4 of the ladder on average moves counts.
guess it, thenthe move: use the page on adding up, reading its n as 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 7. For 4 numbers, 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: no row takes more
the line:why it is allowed: A row's moves are its inversions, by line 2, and never more than its pairs, lines 4 to 7.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
count it yourself
Follow every step on 4, 3, 2, 1, one of the dearest rows, then check the comparisons against .
| step | the row | what happens | comparisons | moves |
|---|---|---|---|---|
| 1 | 4, 3, 2, 1 | There are 4 numbers in a row. The first one on its own is in order, so start with the second.4, 3, 2, 1 | 0 | 0 |
| 2 | 4, 3, 2, 1 | Pick up 3 and carry it left past every bigger number before it.4, 3, 2, 1 | 0 | 0 |
| 3 | 4, 3, 2, 1 | 4 is bigger than 3, so 4 has to make room.4, 3, 2, 1 | 1 | 0 |
| 4 | 3, 4, 2, 1 | 4 moves one place right to make room, and 3 moves one place left.3, 4, 2, 1 | 1 | 1 |
| 5 | 3, 4, 2, 1 | 3 has reached the front: there is nothing left of it to compare with.3, 4, 2, 1 | 1 | 1 |
| 6 | 3, 4, 2, 1 | 3 is in its place among the numbers picked up so far, so the first 2 numbers are in order.3, 4, 2, 1 | 1 | 1 |
| 7 | 3, 4, 2, 1 | Pick up 2 and carry it left past every bigger number before it.3, 4, 2, 1 | 1 | 1 |
| 8 | 3, 4, 2, 1 | 4 is bigger than 2, so 4 has to make room.3, 4, 2, 1 | 2 | 1 |
| 9 | 3, 2, 4, 1 | 4 moves one place right to make room, and 2 moves one place left.3, 2, 4, 1 | 2 | 2 |
| 10 | 3, 2, 4, 1 | 3 is bigger than 2, so 3 has to make room.3, 2, 4, 1 | 3 | 2 |
| 11 | 2, 3, 4, 1 | 3 moves one place right to make room, and 2 moves one place left.2, 3, 4, 1 | 3 | 3 |
| 12 | 2, 3, 4, 1 | 2 has reached the front: there is nothing left of it to compare with.2, 3, 4, 1 | 3 | 3 |
| 13 | 2, 3, 4, 1 | 2 is in its place among the numbers picked up so far, so the first 3 numbers are in order.2, 3, 4, 1 | 3 | 3 |
| 14 | 2, 3, 4, 1 | Pick up 1 and carry it left past every bigger number before it.2, 3, 4, 1 | 3 | 3 |
| 15 | 2, 3, 4, 1 | 4 is bigger than 1, so 4 has to make room.2, 3, 4, 1 | 4 | 3 |
| 16 | 2, 3, 1, 4 | 4 moves one place right to make room, and 1 moves one place left.2, 3, 1, 4 | 4 | 4 |
| 17 | 2, 3, 1, 4 | 3 is bigger than 1, so 3 has to make room.2, 3, 1, 4 | 5 | 4 |
| 18 | 2, 1, 3, 4 | 3 moves one place right to make room, and 1 moves one place left.2, 1, 3, 4 | 5 | 5 |
| 19 | 2, 1, 3, 4 | 2 is bigger than 1, so 2 has to make room.2, 1, 3, 4 | 6 | 5 |
| 20 | 1, 2, 3, 4 | 2 moves one place right to make room, and 1 moves one place left.1, 2, 3, 4 | 6 | 6 |
| 21 | 1, 2, 3, 4 | 1 has reached the front: there is nothing left of it to compare with.1, 2, 3, 4 | 6 | 6 |
| 22 | 1, 2, 3, 4 | 1 is in its place among the numbers picked up so far, so the first 4 numbers are in order.1, 2, 3, 4 | 6 | 6 |
| 23 | 1, 2, 3, 4 | In order, after 6 comparisons and 6 moves.1, 2, 3, 4 | 6 | 6 |
In all, 6 comparisons. The formula from section 4, , gives at : the same.
where you meet it
Insertion sort does real work every day, mostly inside other sorts.
finishing short stretches inside a language's own sort
Python and Java, two programming languages, each come with a sort. Python's is Timsort. So is Java's, for things other than plain numbers, such as words. It finds stretches already in order, called runs, turning a back to front run round, and merges them. A list shorter than 64 items in Python, or 32 in Java, is sorted by binary insertion sort alone. It finds each place by halving, then shifts the bigger items as here. On a longer list, a short run is first stretched the same way. Python's notes say why: on stretches that short it costs less than merging.
source: Tim Peters, listsort.txt and the binarysort comment in Objects/listobject.c, in the CPython source; OpenJDK, java.util.TimSort; Algorithmic Thinking Without the Jargon, volume one, chapter 8
the final insertion sort inside the GNU C++ library's sort
In C++, another language, the GNU C++ library's std::sort is introsort, built on quick sort. It splits the row round pivots, smaller numbers left and bigger right, and stops splitting a part of 16 numbers or fewer. Each such part holds the numbers that belong there, only jumbled. One insertion sort over the whole row then finishes the job, no number sliding out of its part.
source: David Musser, Introspective sorting and selection algorithms, Software Practice and Experience, 1997; the GNU C++ library's stl_algo.h; Algorithmic Thinking Without the Jargon, volume one, chapters 8 and 11
what is used instead
On a long shuffled row insertion sort is far too slow: a million numbers take about 250 billion moves on average. Merge sort and quick sort, each on its own page, take the long rows.
how it compares
Insertion sort beside the other ways to put a row in order, on one plot and in one table. Bubble sort's row speaks of a walk, its word 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.