Skip to content

Insertion sort

ordering

Level 1 of 3

Also called Straight insertion.

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 row15, 35, 45, 25
after move 115, 35, 25, 45
after move 215, 25, 35, 45
The 35 and the 45 each stay after one comparison. The 25 trades places with the 45, then the 35, and stops at the 15, which is not bigger. 5 comparisons and 2 moves.
the row42, 7, 31, 18, 56, 23, 12, 49
after slide 17, 42, 31, 18, 56, 23, 12, 49
after slide 27, 31, 42, 18, 56, 23, 12, 49
after slide 37, 18, 31, 42, 56, 23, 12, 49
after slide 47, 18, 31, 42, 56, 23, 12, 49
after slide 57, 18, 23, 31, 42, 56, 12, 49
after slide 67, 12, 18, 23, 31, 42, 56, 49
after slide 77, 12, 18, 23, 31, 42, 49, 56
The row of the run below, after each slide. Slide 1 takes the 7 to the front, slide 4 leaves the 56 where it is, and slide 6 takes the 12 past five bigger numbers. 19 comparisons and 13 moves.
A short shuffle: 8 moments of its 49 steps, the steps between them left for the watch page
  1. step 2 of 49

    427311856231249

    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

    watch from here

  2. step 5 of 49

    742311856231249

    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

    watch from here

  3. step 10 of 49

    731421856231249

    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

    watch from here

  4. step 20 of 49

    718314256231249

    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

    watch from here

  5. step 31 of 49

    718233142561249

    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

    watch from here

  6. step 42 of 49

    712182331425649

    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

    watch from here

  7. step 48 of 49

    712182331424956

    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

    watch from here

  8. step 49 of 49

    712182331424956

    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.

    watch from here

the steps, in plain words
  1. for each number from the second to the lastPython line 10
  2. take it out of the rowPython lines 11 and 12
  3. while the number on its left is biggerPython line 13
  4. move that number one place rightPython lines 14 and 15
  5. 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

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

  • 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
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 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestalready in order, one of the cheapest rowsaverageshuffled, different numbers in a random order, every order as likelyworstback to front, one of the dearest rows
comparisonsn−1n - 1n(n−1)4+n−H(n)\frac{n(n - 1)}{4} + n - H(n)n(n−1)2\frac{n(n - 1)}{2}
movesnonen(n−1)4\frac{n(n - 1)}{4}n(n−1)2\frac{n(n - 1)}{2}
how the comparisons grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)
ceiling, OOO(n)O(n)O(n2)O(n^2)O(n2)O(n^2)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n2)\Omega(n^2)Ω(n2)\Omega(n^2)

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 5comparisonsmoves
1, 2, 3, 4, 540
all 120 orders, on averageabout 7.725
5, 4, 3, 2, 11010
In order, each number placed stops at its first comparison. Back to front, each slides to the front, 1 + 2 + 3 + 4 = 10. 5 numbers stand in 5 × 4 × 3 × 2 × 1 = 120 orders, 5 choices for place 1, then 4, and on. They average 5 moves, 5 times 4 over 4, and about 7.72 comparisons, section 4's averages for 5 numbers.
rowcomparisons by each number placedin all
1, 2, 3, 41, 1, 13
2, 1, 3, 41, 1, 13
4, 3, 2, 11, 2, 36
1, 4, 3, 21, 2, 36
On 2, 1, 3, 4 the 1 reaches the front after one comparison, as cheap as in order. On 1, 4, 3, 2 the 1 stops every slide, and the total matches back to front.

where the formula comes from

Each count above, worked out in small steps. Every step names the line it uses.

Why does a row back to front cost n(n−1)2\frac{n(n - 1)}{2} comparisons, the most any row can?
  1. the move: count what one number can cost

    the line:
    the number at place k makesat most k−1 comparisons\begin{gathered} \text{the number at place } k \text{ makes} \\ \text{at most } k - 1 \text{ comparisons} \end{gathered}

    why it is allowed: k−1k - 1 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.

  2. the move: no row costs more

    the line:
    no row of n numbers costs morethan 1+2+⋯+(n−1)\begin{gathered} \text{no row of } n \text{ numbers costs more} \\ \text{than } 1 + 2 + \dots + (n - 1) \end{gathered}

    why it is allowed: By line 1, places 2 to nn cost at most 1, 2, and on up to n−1n - 1. For 4 numbers, 1 + 2 + 3.

  3. the move: see the slides on a row back to front

    the line:
    on a row back to front,each number slidesall the way to the front\begin{gathered} \text{on a row back to front,} \\ \text{each number slides} \\ \text{all the way to the front} \end{gathered}
    the row4, 3, 2, 1
    after slide 13, 4, 2, 1
    after slide 22, 3, 4, 1
    after slide 31, 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.

  4. the move: so each costs its most

    the line:
    on a row back to front,the number at place kmakes k−1 comparisons\begin{gathered} \text{on a row back to front,} \\ \text{the number at place } k \\ \text{makes } k - 1 \text{ comparisons} \end{gathered}

    why it is allowed: By line 3 it meets all k−1k - 1, the most line 1 allows. On 4, 3, 2, 1 the 3, the 2 and the 1 make 1, 2 and 3.

  5. the move: add up the comparisons of the numbers placed

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

    why it is allowed: CC is the comparisons on a row back to front, line 4 added over places 2 to nn.

  6. the move: so this row is one of the dearest

    the line:
    a row back to front isone of the dearest\begin{gathered} \text{a row back to front is} \\ \text{one of the dearest} \end{gathered}

    why it is allowed: By lines 2 and 5.

  7. the move: use the page on adding up, reading its n as 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 5'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.

  8. 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.

  9. 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.

  10. 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.

  11. 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.

  12. the move: a ceiling

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

    why it is allowed: Line 11 takes something away from n22\frac{n^2}{2}.

  13. the move: read it as a bound

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

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

  14. the move: a fact for the floor

    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: 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 n2n^2 alone. Times 4, this line says twice nn is at most nn times nn, true from 2 numbers on.

  15. 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: Line 11 takes away n2\frac{n}{2}, at most line 14's n24\frac{n^2}{4}, and taking away more leaves less. For 10 numbers, 45 is at least 50 less 25.

  16. 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.

  17. the move: read it as a bound

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

    why it is allowed: By line 16, CC stays 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.

  18. the move: a ceiling and a floor together

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

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

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

Why does a row already in order cost only n−1n - 1 comparisons, the fewest any row can?
  1. the move: no row costs less

    the line:
    no row costs fewer than n−1\text{no row costs fewer than } n - 1

    why it is allowed: Each number from place 2 on has a left neighbour, so its slide starts with a comparison.

  2. the move: on a row in order, one comparison each

    the line:
    C=n−1C = n - 1
    placingcompared witha move
    21no
    32no
    43no
    54no
    On 1, 2, 3, 4, 5: 4 comparisons, which is 5 less 1, and no move.

    why it is allowed: CC is now the comparisons on a row in order. Each first comparison finds a number not bigger and stops the slide.

  3. the move: so this row is a cheapest one

    the line:
    a row already in orderis a cheapest row\begin{gathered} \text{a row already in order} \\ \text{is a cheapest row} \end{gathered}

    why it is allowed: By lines 1 and 2.

  4. the move: a ceiling

    the line:
    C≤nC \le n

    why it is allowed: Line 2 takes 1 from nn, which leaves less than nn.

  5. the move: read it as a bound

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

    why it is allowed: By line 4.

  6. 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 once nn is 2 or more.

  7. the move: a floor

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

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

  8. the move: tidy the floor

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

    why it is allowed: nn less half of nn is half of nn.

  9. the move: read it as a bound

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

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

  10. the move: a ceiling and a floor together

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

    why it is allowed: Lines 9 and 5 bound CC by the same growth, nn.

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

How many moves does a shuffle take, on average?
  1. the move: see what one move does

    the line:
    a move swaps the numberbeing placed with abigger neighbour\begin{gathered} \text{a move swaps the number} \\ \text{being placed with a} \\ \text{bigger neighbour} \end{gathered}

    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.

  2. the move: a move mends one inversion

    the line:
    a move mends oneinversion and makesno new one\begin{gathered} \text{a move mends one} \\ \text{inversion and makes} \\ \text{no new one} \end{gathered}
    pairin 4, 9, 7, 2in 4, 7, 9, 2
    4 and 9rightright
    4 and 7rightright
    4 and 2wrongwrong
    9 and 7wrongright
    9 and 2wrongwrong
    7 and 2wrongwrong
    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.

  3. the move: count the moves as inversions

    the line:
    the moves are exactly theinversions the row starts with\begin{gathered} \text{the moves are exactly the} \\ \text{inversions the row starts with} \end{gathered}

    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.

  4. the move: count the pairs

    the line:
    a row of n numbers holds1+2+⋯+(n−1) pairs\begin{gathered} \text{a row of } n \text{ numbers holds} \\ 1 + 2 + \dots + (n - 1) \text{ pairs} \end{gathered}

    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 nn with n−1n - 1. For 4 numbers, 1 + 2 + 3.

  5. the move: each pair is wrong half the time

    the line:
    each pair stands wrong inexactly half of the shuffles\begin{gathered} \text{each pair stands wrong in} \\ \text{exactly half of the shuffles} \end{gathered}
    pair 1 and 2 wrongtraded, now right
    2, 1, 31, 2, 3
    2, 3, 11, 3, 2
    3, 2, 13, 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.

  6. the move: count the wrong pairs two ways

    the line:
    adding up the wrong pairsshuffle by shuffle, orpair by pair, givesthe same total\begin{gathered} \text{adding up the wrong pairs} \\ \text{shuffle by shuffle, or} \\ \text{pair by pair, gives} \\ \text{the same total} \end{gathered}
    shuffle1 and 21 and 32 and 3wrong pairs
    1, 2, 30
    1, 3, 2x1
    2, 1, 3x1
    2, 3, 1xx2
    3, 1, 2xx2
    3, 2, 1xxx3
    in all3339
    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.

  7. the move: add up the wrong pairs pair by pair

    the line:
    the wrong pairs of everyshuffle, added, come tothe number of pairstimes half the numberof shuffles\begin{gathered} \text{the wrong pairs of every} \\ \text{shuffle, added, come to} \\ \text{the number of pairs} \\ \text{times half the number} \\ \text{of shuffles} \end{gathered}

    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.

  8. the move: divide by the shuffles

    the line:
    on average, a shuffleholds half as manywrong pairs as pairs\begin{gathered} \text{on average, a shuffle} \\ \text{holds half as many} \\ \text{wrong pairs as pairs} \end{gathered}

    why it is allowed: Line 7's total over the number of shuffles. For 3 numbers, 9 over 6 is 1.5.

  9. the move: the average moves are the average wrong pairs

    the line:
    on average, a shufflemakes half as manymoves as pairs\begin{gathered} \text{on average, a shuffle} \\ \text{makes half as many} \\ \text{moves as pairs} \end{gathered}

    why it is allowed: By line 3 each shuffle's moves are its wrong pairs, so their averages match, line 8's.

  10. the move: put in the count of pairs

    the line:
    M=12×(1+2+⋯+(n−1))M = \frac{1}{2} \times \bigl(1 + 2 + \dots + (n - 1)\bigr)

    why it is allowed: MM is the moves averaged over every shuffle of nn different numbers. By line 9, half the pairs of line 4.

  11. the move: use the page on adding up, reading its n as n - 1

    the line:
    M=12×(n−1)((n−1)+1)2M = \frac{1}{2} \times \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 7. For 3 numbers, 2 times 3, halved, is 3.

  12. the move: tidy the bracket

    the line:
    M=12×(n−1)n2M = \frac{1}{2} \times \frac{(n - 1)n}{2}

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

  13. the move: multiply the fractions

    the line:
    M=(n−1)n4M = \frac{(n - 1)n}{4}

    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.

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

    the line:
    M=n(n−1)4M = \frac{n(n - 1)}{4}

    why it is allowed: The same product.

  15. the move: multiply out the bracket

    the line:
    M=n2−n4M = \frac{n^2 - n}{4}

    why it is allowed: nn lots of nn make n2n^2, and nn lots of 1 make nn.

  16. the move: take a quarter of each part

    the line:
    M=n24−n4M = \frac{n^2}{4} - \frac{n}{4}

    why it is allowed: A quarter of a difference is the difference of the quarters.

  17. the move: a ceiling

    the line:
    M≤n24M \le \frac{n^2}{4}

    why it is allowed: Line 16 takes something away from n24\frac{n^2}{4}.

  18. the move: read it as a bound

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

    why it is allowed: By line 17.

  19. the move: a fact for the floor

    the line:
    n4≤n28 for n≥2\frac{n}{4} \le \frac{n^2}{8} \text{ for } n \ge 2
    nnn4\frac{n}{4}n28\frac{n^2}{8}
    20.50.5
    412
    102.512.5
    100251,250
    Equal at 2 numbers, then the eighth of n squared pulls ever further ahead.

    why it is allowed: Times 8, this says twice nn is at most nn times nn, as at the first ladder's line 14.

  20. the move: a floor

    the line:
    M≥n24−n28 for n≥2M \ge \frac{n^2}{4} - \frac{n^2}{8} \text{ for } n \ge 2

    why it is allowed: Line 16 takes away n4\frac{n}{4}, at most line 19's n28\frac{n^2}{8}, and taking away more leaves less. For 10 numbers, 22.5 is at least 25 less 12.5.

  21. the move: tidy the floor

    the line:
    M≥n28 for n≥2M \ge \frac{n^2}{8} \text{ for } n \ge 2

    why it is allowed: A quarter less an eighth is an eighth.

  22. the move: read it as a bound

    the line:
    M∈Ω(n2)M \in \Omega(n^2)
    10210410610810101012101410110210310410510610710110210310410510610710810910101011101210131014101102103104105106107
    • the average moves, n(n−1)4\frac{n(n - 1)}{4}
    • the ceiling of line 17, n24\frac{n^2}{4}
    • the floor of line 21, n28\frac{n^2}{8}
    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.

  23. the move: a ceiling and a floor together

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

    why it is allowed: Lines 22 and 18 bound MM by the same growth, n2n^2.

try it on small rows: over every order of 3 numbers, the average is M=1.5M = 1.5

How many comparisons does a shuffle take, on average?
  1. the move: count one number's comparisons

    the line:
    each number placed makesone comparison per move,and one more unless itreaches the front\begin{gathered} \text{each number placed makes} \\ \text{one comparison per move,} \\ \text{and one more unless it} \\ \text{reaches the front} \end{gathered}

    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.

  2. the move: add over the numbers placed

    the line:
    the comparisons arethe moves, plus n−1,less the numbers thatreach the front\begin{gathered} \text{the comparisons are} \\ \text{the moves, plus } n - 1, \\ \text{less the numbers that} \\ \text{reach the front} \end{gathered}
    shufflemovesreach the frontcomparisons
    1, 2, 3002
    1, 3, 2103
    2, 1, 3112
    2, 3, 1213
    3, 1, 2213
    3, 2, 1323
    in all9516
    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 n−1n - 1 numbers placed. On 2, 5, 1, 4, 3: 5 moves, plus 4, less 1 for the 1, make 8.

  3. the move: see which numbers reach the front

    the line:
    a number reaches thefront when it is smallerthan every numberbefore it\begin{gathered} \text{a number reaches the} \\ \text{front when it is smaller} \\ \text{than every number} \\ \text{before it} \end{gathered}
    the shuffle3, 1, 4, 2
    after slide 11, 3, 4, 2
    after slide 21, 3, 4, 2
    after slide 31, 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.

  4. the move: each place is as likely

    the line:
    each of the first k placesis as likely as any otherto hold the smallestnumber in them\begin{gathered} \text{each of the first } k \text{ places} \\ \text{is as likely as any other} \\ \text{to hold the smallest} \\ \text{number in them} \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. 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 kk 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 kk places hold it equally often, and so do all kk.

  5. the move: the chance at place k

    the line:
    the number at place k is a newsmallest with chance 1 over k\begin{gathered} \text{the number at place } k \text{ is a new} \\ \text{smallest with chance 1 over } k \end{gathered}
    shuffleplace 2place 3
    1, 2, 300
    1, 3, 200
    2, 1, 310
    2, 3, 101
    3, 1, 210
    3, 2, 111
    in all32
    average1 over 21 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 kk. That smallest stands at one place in each shuffle, and by line 4 at each place equally often, so at place kk in 1 of every kk. In the picture, place 2 holds a new smallest in 3 of the 6, a half, and place 3 in 2, a third.

  6. the move: average the three pieces

    the line:
    on average, thecomparisons are theaverage moves, plus n−1,less the average countthat reach the front\begin{gathered} \text{on average, the} \\ \text{comparisons are the} \\ \text{average moves, plus } n - 1, \\ \text{less the average count} \\ \text{that reach the front} \end{gathered}

    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 n−1n - 1 averages to itself. For 3 numbers, line 2's 9 moves, plus 2 times 6, less 5, make 16 over 6 shuffles.

  7. the move: the count is a sum of tallies

    the line:
    the count that reach the frontis a sum of one tally per placefrom 2 to n, each 1 or 0\begin{gathered} \text{the count that reach the front} \\ \text{is a sum of one tally per place} \\ \text{from 2 to } n \text{, each 1 or 0} \end{gathered}

    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.

  8. the move: average tally by tally

    the line:
    the average count is the sumof the tallies’ averages\begin{gathered} \text{the average count is the sum} \\ \text{of the tallies' averages} \end{gathered}

    why it is allowed: Line 6's rule, for a sum of tallies.

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

    the line:
    the tally at place kaverages to 1 over k\begin{gathered} \text{the tally at place } k \\ \text{averages to 1 over } k \end{gathered}

    why it is allowed: A column of 1s and 0s averages to its share of 1s, which line 5 finds is 1 over kk.

  10. the move: count those that reach the front

    the line:
    on average, this manynumbers reach the front:12+13+⋯+1n\begin{gathered} \text{on average, this many} \\ \text{numbers reach the front:} \\ \frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{n} \end{gathered}

    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.

  11. the move: put the pieces together

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

    why it is allowed: AA is the comparisons averaged over every shuffle of nn different numbers. Into line 6 go the ladder before's average moves and line 10's count.

  12. the move: name the sum

    the line:
    A=n(n−1)4+(n−1)−(H(n)−1)A = \frac{n(n - 1)}{4} + (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.

  13. the move: open the bracket

    the line:
    A=n(n−1)4+(n−1)−H(n)+1A = \frac{n(n - 1)}{4} + (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.

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

    the line:
    A=n(n−1)4+(n−1)+1−H(n)A = \frac{n(n - 1)}{4} + (n - 1) + 1 - H(n)

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

  15. the move: collect the ones

    the line:
    A=n(n−1)4+n−H(n)A = \frac{n(n - 1)}{4} + n - H(n)

    why it is allowed: (n−1)+1(n - 1) + 1 is nn. For 3 numbers, 1.5 plus 3 less about 1.83 is about 2.67, as line 2's 16 over 6.

  16. the move: a floor from the moves

    the line:
    A≥n(n−1)4A \ge \frac{n(n - 1)}{4}

    why it is allowed: Every move follows a comparison, so AA is at least the ladder before's average moves.

  17. the move: a simpler floor

    the line:
    A≥n28 for n≥2A \ge \frac{n^2}{8} \text{ for } n \ge 2

    why it is allowed: By the ladder before, lines 14 to 21.

  18. the move: read it as a bound

    the line:
    A∈Ω(n2)A \in \Omega(n^2)

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

  19. the move: a ceiling from the dearest rows

    the line:
    A≤n(n−1)2A \le \frac{n(n - 1)}{2}
    numbersfloor, line 16the averageceiling, line 19
    31.5about 2.673
    55about 7.7210
    814about 19.2828
    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.

  20. the move: a simpler ceiling

    the line:
    A≤n22A \le \frac{n^2}{2}

    why it is allowed: By the first ladder's lines 11 and 12.

  21. the move: read it as a bound

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

    why it is allowed: By line 20.

  22. the move: a ceiling and a floor together

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

    why it is allowed: Lines 18 and 21 bound AA by the same growth, n2n^2. For 1,000 numbers H(n)H(n) is about 7.5, beside about 250,000 from the moves.

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

Why does a row back to front take n(n−1)2\frac{n(n - 1)}{2} moves, the most any row can?
  1. the move: every pair is wrong

    the line:
    on a row back to front,every pair is an inversion\begin{gathered} \text{on a row back to front,} \\ \text{every pair is an inversion} \end{gathered}

    why it is allowed: Each number is smaller than every number before it. All 6 pairs of 4, 3, 2, 1 are wrong.

  2. the move: the moves are the inversions

    the line:
    one move for each inversionthe row starts with\begin{gathered} \text{one move for each inversion} \\ \text{the row starts with} \end{gathered}

    why it is allowed: Line 3 of the ladder on average moves.

  3. the move: one move for each pair

    the line:
    a row back to front makesone move for each pair\begin{gathered} \text{a row back to front makes} \\ \text{one move for each pair} \end{gathered}
    the row4, 3, 2, 1
    after move 13, 4, 2, 1
    after move 23, 2, 4, 1
    after move 32, 3, 4, 1
    after move 42, 3, 1, 4
    after move 52, 1, 3, 4
    after move 61, 2, 3, 4
    6 moves, one for each of the 6 pairs.

    why it is allowed: By lines 1 and 2.

  4. the move: put in the count of pairs

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

    why it is allowed: WW is this row's moves. By line 3 they are its pairs, which line 4 of the ladder on average moves counts.

  5. the move: use the page on adding up, reading its n as n - 1

    the line:
    W=(n−1)((n−1)+1)2W = \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 7. For 4 numbers, 6.

  6. the move: tidy the bracket

    the line:
    W=(n−1)n2W = \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:
    W=n(n−1)2W = \frac{n(n - 1)}{2}

    why it is allowed: The same product.

  8. the move: no row takes more

    the line:
    no row takes more thann(n−1)2 moves\begin{gathered} \text{no row takes more than} \\ \frac{n(n - 1)}{2} \text{ moves} \end{gathered}

    why it is allowed: A row's moves are its inversions, by line 2, and never more than its pairs, lines 4 to 7.

try it with a small nn: at n=4n = 4, line 4 gives W=6W = 6, 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 n(n−1)2\frac{n(n - 1)}{2}.

4, 3, 2, 1, every step written down
stepthe rowwhat happenscomparisonsmoves
14, 3, 2, 1There are 4 numbers in a row. The first one on its own is in order, so start with the second.4, 3, 2, 100
24, 3, 2, 1Pick up 3 and carry it left past every bigger number before it.4, 3, 2, 100
34, 3, 2, 14 is bigger than 3, so 4 has to make room.4, 3, 2, 110
43, 4, 2, 14 moves one place right to make room, and 3 moves one place left.3, 4, 2, 111
53, 4, 2, 13 has reached the front: there is nothing left of it to compare with.3, 4, 2, 111
63, 4, 2, 13 is in its place among the numbers picked up so far, so the first 2 numbers are in order.3, 4, 2, 111
73, 4, 2, 1Pick up 2 and carry it left past every bigger number before it.3, 4, 2, 111
83, 4, 2, 14 is bigger than 2, so 4 has to make room.3, 4, 2, 121
93, 2, 4, 14 moves one place right to make room, and 2 moves one place left.3, 2, 4, 122
103, 2, 4, 13 is bigger than 2, so 3 has to make room.3, 2, 4, 132
112, 3, 4, 13 moves one place right to make room, and 2 moves one place left.2, 3, 4, 133
122, 3, 4, 12 has reached the front: there is nothing left of it to compare with.2, 3, 4, 133
132, 3, 4, 12 is in its place among the numbers picked up so far, so the first 3 numbers are in order.2, 3, 4, 133
142, 3, 4, 1Pick up 1 and carry it left past every bigger number before it.2, 3, 4, 133
152, 3, 4, 14 is bigger than 1, so 4 has to make room.2, 3, 4, 143
162, 3, 1, 44 moves one place right to make room, and 1 moves one place left.2, 3, 1, 444
172, 3, 1, 43 is bigger than 1, so 3 has to make room.2, 3, 1, 454
182, 1, 3, 43 moves one place right to make room, and 1 moves one place left.2, 1, 3, 455
192, 1, 3, 42 is bigger than 1, so 2 has to make room.2, 1, 3, 465
201, 2, 3, 42 moves one place right to make room, and 1 moves one place left.1, 2, 3, 466
211, 2, 3, 41 has reached the front: there is nothing left of it to compare with.1, 2, 3, 466
221, 2, 3, 41 is in its place among the numbers picked up so far, so the first 4 numbers are in order.1, 2, 3, 466
231, 2, 3, 4In order, after 6 comparisons and 6 moves.1, 2, 3, 466

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

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.

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 sortselection sortshell sortquick sortrandomised quick sortmerge sortheap sortinsertion sort10110210310410510610710810910101011101210131014101102103104105106107bubble sortcocktail shaker sortselection sortshell sortquick sortrandomised quick sortmerge sortheap sortinsertion 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