Skip to content

Shell sort

ordering

Level 2 of 3

Also called Diminishing increment sort.

how it works

The idea, three pictures, then one row sorted step by step.

Shell sort puts a row of numbers in order, smallest first. It is insertion sort with long jumps first. A pass with the gap 4 compares each number from place 5 on with the number 4 places to its left. While that one is bigger, the two trade places, a move. The gaps are 1, 4, 13, 40 and on, each three times the one before and 1 more, a list Donald Knuth suggested. The sort uses every gap below the row's length, the largest first, so its last pass is insertion sort. One long move can mend several wrong pairs at once, and make a few. Donald Shell published the sort in 1959. A long move can carry a number past an equal one, so equal numbers may lose their order.

973524start12 wrong pairs273594move 15 wrong pairs243597move 22 wrong pairs234597move 31 wrong pair234579move 4no wrong pairsa wrong pair, bigger before smallerjust swappedthe pairs it mendeda pair it made
9, 7, 3, 5, 2, 4, move by move. Moves 1 and 2 jump 4 places and take the wrong pairs from 12 to 5, then 2; move 2 mends 5 and makes 2, the red arcs. Moves 3 and 4 take one each. Insertion sort makes 12 moves, one per wrong pair.
the gap 4 pass: 4 comparisons, 1 move427311856231249startthe gap 1 pass: 14 comparisons, 8 moves427121856233149after gap 4712182331424956after gap 1a pair compareda pair tradedmoved by the pass beforethe row at the end
The run below, pass by pass. The gap 4 pass trades only 31 and 12; insertion sort does the rest. 18 comparisons and 9 moves in all, where insertion sort makes 19 and 13.
2a2b2c2d1start12b2c2d2amove 1
2, 2, 2, 2, 1, move by move, the 2s told apart as 2a to 2d. The one move carries 2a past the other three.
A short shuffle: 8 moments of its 44 steps, the steps between them left for the watch page
  1. step 1 of 44

    427311856231249

    There are 8 numbers in a row. Sort the numbers 4 places apart first, then the neighbours.

    what it remembers to know where it is
    gap
    not yet
    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

  2. step 4 of 44

    427311856231249

    42 is not bigger than 56, so 56 stops here.

    what it remembers to know where it is
    gap
    4
    number being placed
    56
    its place now
    5

    watch from here

  3. step 8 of 44

    427311856231249

    31 is bigger than 12, so 31 has to make room.

    what it remembers to know where it is
    gap
    4
    number being placed
    12
    its place now
    7

    watch from here

  4. step 9 of 44

    427121856233149

    31 jumps 4 places right to make room, and 12 jumps the same distance left.

    what it remembers to know where it is
    gap
    4
    number being placed
    12
    its place now
    3

    watch from here

  5. step 13 of 44

    427121856233149

    Now the last pass: compare neighbours, as plain insertion sort does.

    what it remembers to know where it is
    gap
    1
    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

  6. step 16 of 44

    742121856233149

    42 jumps one place right to make room, and 7 jumps the same distance left.

    what it remembers to know where it is
    gap
    1
    number being placed
    7
    its place now
    1

    watch from here

  7. step 42 of 44

    712182331424956

    56 jumps one place right to make room, and 49 jumps the same distance left.

    what it remembers to know where it is
    gap
    1
    number being placed
    49
    its place now
    7

    watch from here

  8. step 44 of 44

    712182331424956

    In order, after 18 comparisons and 9 moves.

    what it remembers to know where it is
    gap
    not yet
    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 gap, from the largest down to 1Python lines 10, 11, 12, 13 and 21
  2. for each number from the gap onwardsPython line 14
  3. pick it upPython lines 15 and 16
  4. while the number a gap to its left is biggerPython line 17
  5. move that number a gap rightPython lines 18 and 19
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 shell_sort(numbers):
    """Put a list of numbers in order, smallest first, in the list itself.

    Sort the numbers a long gap apart first, then a shorter gap, and so on
    down to a gap of 1, which is plain insertion sort, on a list the long
    gaps have often left nearer to order. The gaps come from a list Knuth
    suggested, 1, 4, 13, 40 and on, each three times the last and one more;
    it uses every one shorter than the list (just 1 for one number).
    """
    gap = 1
    while 3 * gap + 1 < len(numbers):  # the largest gap shorter than the list, or 1
        gap = 3 * gap + 1
    while gap >= 1:  # each gap, the largest first
        for i in range(gap, len(numbers)):  # each number with a number a gap to its left
            placing = numbers[i]  # pick it up
            place = i
            while place >= gap and numbers[place - gap] > placing:  # bigger, a gap to its left
                numbers[place] = numbers[place - gap]  # move that number a gap right
                place -= gap
            numbers[place] = placing  # put the number down in the room made
        gap = (gap - 1) // 3  # the next gap down: 13 gives 4, 4 gives 1, 1 gives 0
    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. At the long end a row in order climbs a little over one step per step, 11.8 times from a million numbers to ten million. The shuffled points, each the mean of 20 shuffles, climb about 1.2 steps per step from 1,000 numbers on. No dearest row is drawn, since none is known for long rows. The flat line labelled a second marks a billion comparisons, about a second of a computer's work.

comparisons, ten times more at each mark up

a secondslope 1.1102104106108101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107

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

  • shuffled, different numbers in a random order, every order as likelypoints only, each measured by a real run, since no single formula for the comparisons of this row is worked out here
  • already in order, a cheapest rowsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, about 12 times the work
what a cheapest row costs, at a billion comparisons a second
nncomparisonstime
1,0005,457about 5.5 microseconds
100,000967,146about 967 microseconds
10,000,000139,238,328about 139 milliseconds

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 Shell 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 (not the dearest row, as
section 3 shows), 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 shell_sort(numbers):
    """Put a list of numbers in order, smallest first, in the list itself.

    Sort the numbers a long gap apart first, then a shorter gap, and so on
    down to a gap of 1, which is plain insertion sort, on a list the long
    gaps have often left nearer to order. The gaps come from a list Knuth
    suggested, 1, 4, 13, 40 and on, each three times the last and one more;
    it uses every one shorter than the list (just 1 for one number).
    """
    gap = 1
    while 3 * gap + 1 < len(numbers):  # the largest gap shorter than the list, or 1
        gap = 3 * gap + 1
    while gap >= 1:  # each gap, the largest first
        for i in range(gap, len(numbers)):  # each number with a number a gap to its left
            placing = numbers[i]  # pick it up
            place = i
            while place >= gap and numbers[place - gap] > placing:  # bigger, a gap to its left
                numbers[place] = numbers[place - gap]  # move that number a gap right
                place -= gap
            numbers[place] = placing  # put the number down in the room made
        gap = (gap - 1) // 3  # the next gap down: 13 gives 4, 4 gives 1, 1 gives 0
    return numbers


def count(row):
    """How many comparisons Shell sort makes on this row."""
    Counted.comparisons = 0
    shell_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

In order, each number picked up is compared once and stays put, the fewest any row costs. A shuffled row has no formula known for every length, so the grid gives ceilings and a floor. No dearest row can be named for every length, so no worst case column.

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, a cheapest rowaverageshuffled, different numbers in a random order, every order as likely
comparisons(n−1)+(n−4)+(n−13)+…(n - 1) + (n - 4) + (n - 13) + \dots, one term for each gap below nnnot known; at least the best case, and at most 3(n−1)n2\frac{3(n - 1)n}{2}
movesnonenot known; at most (n−1)n2\frac{(n - 1)n}{2}
how the comparisons grow in each case
tight, Θ\ThetaΘ(n log⁡2 n)\Theta(n \,\log_2\, n)not known
ceiling, OOO(n log⁡2 n)O(n \,\log_2\, n)O(n2)O(n^2)
floor, Ω\OmegaΩ(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)

extra memory: a few spare places (the gap, the number picked up, its place), the same however long the row

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

row of 8comparisonsmoves
1, 2, 3, 4, 5, 6, 7, 8110
all 40,320 orders, on averageabout 17.9210
8, 7, 6, 5, 4, 3, 2, 12016
7, 5, 3, 1, 8, 6, 4, 22618
8 numbers have 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1 = 40,320 orders, 8 choices for place 1, then 7, and on. None costs more than 26. Back to front is not among the dearest, nor at any length from 5 to 8.
rowShell sortinsertion sort
1,000 numbers in order5,457999
7, 5, 3, 1, 8, 6, 4, 22622
the same 20 shuffles of 1,000, on averageabout 13,991about 249,769
Comparisons. In order, 1,000 numbers take one pass for each of the gaps 1, 4, 13, 40, 121 and 364. That is 999 + 996 + 987 + 960 + 879 + 636 = 5,457. The long passes cost more on the first two rows and save far more on the shuffles.
the gap 4 pass: 4 comparisons, no move75318642startthe gap 1 pass: 22 comparisons, 18 moves75318642after gap 412345678after gap 1a pair comparedthe row at the end
The trap's row, pass by pass. The gap 4 pass finds its 4 pairs in order and moves nothing, so insertion sort's 22 comparisons follow.

where the formula comes from

Each count in section 3, in small steps. Only the row in order has a formula; the rest get floors and ceilings.

Why does a row already in order take (n−1)+(n−4)+(n−13)+…(n - 1) + (n - 4) + (n - 13) + \dots comparisons, the fewest any row takes, and what ceiling holds?
  1. the move: count one pass on a row in order

    the line:
    on a row in order,the pass with gap hpicks up places h+1 to nand compares n−h times\begin{gathered} \text{on a row in order,} \\ \text{the pass with gap } h \\ \text{picks up places } h + 1 \text{ to } n \\ \text{and compares } n - h \text{ times} \end{gathered}
    the gap 4 pass: 4 comparisons, no move712182331424956startthe gap 1 pass: 7 comparisons, no move712182331424956after gap 4712182331424956after gap 1a pair comparedthe row at the end
    8 numbers in order. 4 comparisons with the gap 4, then 7 with the gap 1, and no move.

    why it is allowed: Each number picked up meets a number no bigger hh places to its left, so it stays put after one comparison. For 8 numbers and the gap 4, places 5 to 8, 4 comparisons.

  2. the move: list the gaps

    the line:
    the gaps 1,4,13,40,…,each three times the onebefore and 1 more;from 2 numbers on, one passfor each gap below n,the largest first and 1 last\begin{gathered} \text{the gaps } 1, 4, 13, 40, \dots \text{,} \\ \text{each three times the one} \\ \text{before and 1 more;} \\ \text{from 2 numbers on, one pass} \\ \text{for each gap below } n \text{,} \\ \text{the largest first and 1 last} \end{gathered}

    why it is allowed: 3 times 1, and 1, makes 4; 3 times 4, and 1, makes 13. So 8 numbers take the gaps 4 and 1.

  3. the move: add up the passes

    the line:
    B=(n−1)+(n−4)+(n−13)+…one term for eachgap below n\begin{gathered} B = (n - 1) + (n - 4) \\ {} + (n - 13) + \dots \\ \text{one term for each} \\ \text{gap below } n \end{gathered}

    why it is allowed: BB is the comparisons on a row in order, lines 1 and 2 added up. For 8 numbers, 7 + 4, which makes 11.

  4. the move: no row costs fewer

    the line:
    no row of n numberscosts fewer than B\begin{gathered} \text{no row of } n \text{ numbers} \\ \text{costs fewer than } B \end{gathered}

    why it is allowed: On any row each pass picks up the same places, each with a number hh places to its left, so each is compared at least once.

  5. 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 3 and 4. Others tie, as 2, 1, 3, 4, 5, 6, 7, 8 also costs 11.

  6. the move: a ceiling for each term

    the line:
    each term of Bis less than n\begin{gathered} \text{each term of } B \\ \text{is less than } n \end{gathered}

    why it is allowed: Each is nn less a gap of at least 1. For 8 numbers, 7 and 4.

  7. the move: add up the ceilings

    the line:
    B≤G×nB \le G \times n

    why it is allowed: GG is how many gaps lie below nn, so by lines 3 and 6, BB is GG terms, each less than nn. For 8 numbers, 11 is at most 2 times 8.

  8. the move: each gap more than doubles

    the line:
    each gap is more thantwice the one before\begin{gathered} \text{each gap is more than} \\ \text{twice the one before} \end{gathered}
    numberlog× 2+ 121831641042133.70
    The gaps 1, 4 and 13 on a line of powers of two, where each step doubles. Each gap sits more than one step right of the one before.

    why it is allowed: By line 2, three times a gap, and 1, is more than twice it.

  9. the move: compare the gaps with the powers of 2

    the line:
    gap number k is at least 2k−1\text{gap number } k \text{ is at least } 2^{k - 1}
    kkgap number kk2k−12^{k - 1}
    111
    242
    3134
    4408
    512116
    Each gap beside the power of 2 with its number, equal at 1, then ever further above.

    why it is allowed: Gap number 1 is 1, 2 to the power 0. Each power of 2 is twice the one before, and each gap more than twice, by line 8. So when one gap is at least its power of 2, the next is too, and so on for ever.

  10. the move: name the largest gap below n

    the line:
    from 2 numbers on,the largest gap below nis gap number G\begin{gathered} \text{from 2 numbers on,} \\ \text{the largest gap below } n \\ \text{is gap number } G \end{gathered}

    why it is allowed: From 2 numbers on the gap 1 is below nn, and the gaps grow, by line 8. So the GG gaps below nn are gap numbers 1 to GG.

  11. the move: use line 9 on the largest gap

    the line:
    gap number G≥2G−1\text{gap number } G \ge 2^{G - 1}

    why it is allowed: Line 9 with GG for kk. For 8 numbers, 4 is at least 2.

  12. the move: the largest gap is at most n

    the line:
    gap number G≤n\text{gap number } G \le n

    why it is allowed: By line 10. For 8 numbers, 4 is at most 8.

  13. the move: put the two together

    the line:
    2G−1≤n2^{G - 1} \le n

    why it is allowed: By lines 11 and 12.

  14. the move: read it as a log

    the line:
    G−1≤log⁡2 nG - 1 \le \log_2\, n

    why it is allowed: Take the log of both sides of line 13. A bigger number has a bigger log, as the page on halving and logarithms shows, and the log of 2 to a power is that power. For 8 numbers, 1 is at most 3.

  15. the move: add 1 to both sides

    the line:
    G≤log⁡2 n+1G \le \log_2\, n + 1

    why it is allowed: Line 14 plus 1.

  16. the move: multiply both sides by n

    the line:
    G×n≤n(log⁡2 n+1)G \times n \le n(\log_2\, n + 1)

    why it is allowed: Line 15 times nn, above zero. For 8 numbers, 16 is at most 32.

  17. the move: put the count of gaps in

    the line:
    B≤n(log⁡2 n+1)B \le n(\log_2\, n + 1)

    why it is allowed: By lines 7 and 16. For 8 numbers, 11 is at most 32.

  18. the move: a fact for a simpler ceiling

    the line:
    1≤log⁡2 n for n≥21 \le \log_2\, n \text{ for } n \ge 2

    why it is allowed: From 2 numbers on nn is at least 2, whose log is 1, and a bigger number has a bigger log.

  19. the move: add the log to both sides

    the line:
     log⁡2 n+1≤log⁡2 n+log⁡2 nfor n≥2\begin{gathered} \,\log_2\, n + 1 \le \log_2\, n + \log_2\, n \\ \text{for } n \ge 2 \end{gathered}

    why it is allowed: Line 18 plus log⁡2 n\log_2\, n.

  20. the move: add like to like

    the line:
    log⁡2 n+1≤2 log⁡2 n for n≥2\log_2\, n + 1 \le 2 \,\log_2\, n \text{ for } n \ge 2

    why it is allowed: Two lots of log⁡2 n\log_2\, n.

  21. the move: multiply both sides by n

    the line:
    n(log⁡2 n+1)≤2n log⁡2 nfor n≥2\begin{gathered} n(\log_2\, n + 1) \le 2n \,\log_2\, n \\ \text{for } n \ge 2 \end{gathered}

    why it is allowed: Line 20 times nn, above zero.

  22. the move: a simpler ceiling

    the line:
    B≤2n log⁡2 n for n≥2B \le 2n \,\log_2\, n \text{ for } n \ge 2

    why it is allowed: By lines 17 and 21. For 8 numbers, 11 is at most 48.

  23. the move: read it as a bound

    the line:
    B∈O(n log⁡2 n)B \in O(n \,\log_2\, n)

    why it is allowed: By line 22, under twice n log⁡2 nn \,\log_2\, n, a fixed multiple.

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

Why does a row already in order take at least n log⁡2 n8\frac{n \,\log_2\, n}{8} comparisons from 4 numbers on, so that its count grows like n log⁡2 nn \,\log_2\, n?
  1. the move: the count from the first ladder

    the line:
    B=(n−1)+(n−4)+(n−13)+…B = (n - 1) + (n - 4) + (n - 13) + \dots

    why it is allowed: The first ladder's line 3. Next, keep only the gaps at most half of nn, each giving at least half of nn, and show there are at least log⁡2 n−12\frac{\log_2\, n - 1}{2} of them.

  2. the move: a short gap's pass

    the line:
    on a row in order, a passwhose gap is at most n2compares at least n2 times\begin{gathered} \text{on a row in order, a pass} \\ \text{whose gap is at most } \frac{n}{2} \\ \text{compares at least } \frac{n}{2} \text{ times} \end{gathered}

    why it is allowed: By the first ladder's line 1 it compares n−hn - h times, and hh is at most half of nn. For 8 numbers, the gap 4's pass compares 4 times.

  3. the move: keep only the short gaps' terms

    the line:
    B≥(n−1)+(n−4)+…one term for each gapat most n2\begin{gathered} B \ge (n - 1) + (n - 4) + \dots \\ \text{one term for each gap} \\ \text{at most } \frac{n}{2} \end{gathered}

    why it is allowed: LL is how many gaps are at most half of nn. The other terms are at least 1 each, so dropping them leaves less. For 20 numbers, 19 + 16 + 7 drops to 19 + 16.

  4. the move: add up the short gaps' floors

    the line:
    B≥L×n2B \ge L \times \frac{n}{2}

    why it is allowed: By lines 2 and 3. For 8 numbers, 11 is at least 2 times 4.

  5. the move: each gap at most four times the one before

    the line:
    each gap is at most fourtimes the one before\begin{gathered} \text{each gap is at most four} \\ \text{times the one before} \end{gathered}
    numberlog× 2+ 121831641042133.70
    The gaps 1, 4 and 13 again. Each sits at most two steps, four times, right of the one before.

    why it is allowed: By the first ladder's line 2 a gap is three times the one before, plus 1, and that 1 is at most the gap before. 13 is at most 4 times 4.

  6. the move: compare the gaps with the powers of 4

    the line:
    gap number k is at most 4k−1\text{gap number } k \text{ is at most } 4^{k - 1}
    kkgap number kk4k−14^{k - 1}
    111
    244
    31316
    44064
    5121256
    Each gap beside the power of 4 with its number, at or below it.

    why it is allowed: As at the first ladder's line 9, turned round. Gap number 1 is 4 to the power 0. Each power of 4 is four times the one before, and each gap at most four times, by line 5, so each gap stays at or below its power.

  7. the move: the first gap above half of n

    the line:
    gap number L+1is above n2\begin{gathered} \text{gap number } L + 1 \\ \text{is above } \frac{n}{2} \end{gathered}
    nngaps at most n2\frac{n}{2}gaps below nngap number L+1L + 1
    81, 41, 413
    301, 4, 131, 4, 1340
    601, 4, 131, 4, 13, 4040
    1001, 4, 13, 401, 4, 13, 40121
    Only at 60 is gap number L+1L + 1 below nn and so given a pass.

    why it is allowed: The gaps grow, by the first ladder's line 8, so the LL short gaps come first and the next is above half of nn. For 8 numbers, 13 is above 4.

  8. the move: so at least half of n

    the line:
    gap number L+1≥n2\text{gap number } L + 1 \ge \frac{n}{2}

    why it is allowed: Above half is at least half.

  9. the move: use line 6 on the next gap

    the line:
    gap number L+1≤4(L+1)−1\text{gap number } L + 1 \le 4^{(L + 1) - 1}

    why it is allowed: Line 6 holds for every gap in the list. For 8 numbers, 13 is at most 4 to the power 2.

  10. the move: tidy the power

    the line:
    gap number L+1≤4L\text{gap number } L + 1 \le 4^L

    why it is allowed: One less than L+1L + 1 is LL.

  11. the move: put the two together

    the line:
    4L≥n24^L \ge \frac{n}{2}

    why it is allowed: By lines 10 and 8. For 8 numbers, 16 is at least 13, which is at least 4.

  12. the move: write the power of 4 as a power of 2

    the line:
    22L≥n22^{2L} \ge \frac{n}{2}

    why it is allowed: Each 4 is 2 × 2. For 8 numbers, 16 is 2 to the power 4.

  13. the move: double both sides

    the line:
    2×22L≥n2 \times 2^{2L} \ge n

    why it is allowed: Line 12 doubled.

  14. the move: one more 2

    the line:
    22L+1≥n2^{2L + 1} \ge n

    why it is allowed: Times 2 is one more 2 in the power. For 8 numbers, 32 is 2 to the power 5.

  15. the move: read it as a log

    the line:
    2L+1≥log⁡2 n2L + 1 \ge \log_2\, n

    why it is allowed: Take the log of both sides of line 14, as at the first ladder's line 14. For 8 numbers, 5 is at least 3.

  16. the move: take 1 off both sides

    the line:
    2L≥log⁡2 n−12L \ge \log_2\, n - 1

    why it is allowed: Line 15 less 1.

  17. the move: halve both sides

    the line:
    L≥log⁡2 n−12L \ge \frac{\log_2\, n - 1}{2}

    why it is allowed: Line 16 halved. For 8 numbers, 2 is at least 1.

  18. the move: multiply both sides by half of n

    the line:
    L×n2≥log⁡2 n−12×n2L \times \frac{n}{2} \ge \frac{\log_2\, n - 1}{2} \times \frac{n}{2}

    why it is allowed: Line 17 times half of nn, above zero.

  19. the move: put the count of short gaps in

    the line:
    B≥log⁡2 n−12×n2B \ge \frac{\log_2\, n - 1}{2} \times \frac{n}{2}

    why it is allowed: By lines 4 and 18. For 8 numbers, 11 is at least 4.

  20. the move: multiply the fractions

    the line:
    B≥n(log⁡2 n−1)4B \ge \frac{n(\log_2\, n - 1)}{4}

    why it is allowed: A half of a half is a quarter.

  21. the move: multiply out the bracket

    the line:
    B≥n log⁡2 n−n4B \ge \frac{n \,\log_2\, n - n}{4}

    why it is allowed: nn times each part of the bracket.

  22. the move: take a quarter of each part

    the line:
    B≥n log⁡2 n4−n4B \ge \frac{n \,\log_2\, n}{4} - \frac{n}{4}

    why it is allowed: A quarter of a difference. For 8 numbers, 6 less 2 is 4.

  23. the move: a fact for the floor

    the line:
    2≤log⁡2 n for n≥42 \le \log_2\, n \text{ for } n \ge 4

    why it is allowed: From 4 numbers on nn is at least 4, whose log is 2, and a bigger number has a bigger log.

  24. the move: multiply both sides by an eighth of n

    the line:
    2n8≤n log⁡2 n8 for n≥4\frac{2n}{8} \le \frac{n \,\log_2\, n}{8} \text{ for } n \ge 4

    why it is allowed: Line 23 times an eighth of nn, above zero.

  25. the move: tidy the left side

    the line:
    n4≤n log⁡2 n8 for n≥4\frac{n}{4} \le \frac{n \,\log_2\, n}{8} \text{ for } n \ge 4

    why it is allowed: Two eighths are a quarter. For 8 numbers, 2 is at most 3.

  26. the move: a floor

    the line:
    B≥n log⁡2 n4−n log⁡2 n8 for n≥4B \ge \frac{n \,\log_2\, n}{4} - \frac{n \,\log_2\, n}{8} \text{ for } n \ge 4

    why it is allowed: Line 22 takes away a quarter of nn, at most line 25's eighth of n log⁡2 nn \,\log_2\, n, and taking away more leaves less. For 8 numbers, 6 less 3 is 3.

  27. the move: tidy the floor

    the line:
    B≥n log⁡2 n8 for n≥4B \ge \frac{n \,\log_2\, n}{8} \text{ for } n \ge 4

    why it is allowed: A quarter less an eighth. For 8 numbers, 11 is at least 3.

  28. the move: read it as a bound

    the line:
    B∈Ω(n log⁡2 n)B \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 27, an eighth being a fixed multiple, from 4 numbers on.

  29. the move: the ceiling from the first ladder

    the line:
    B≤2n log⁡2 n for n≥2B \le 2n \,\log_2\, n \text{ for } n \ge 2

    why it is allowed: The first ladder's line 22.

  30. the move: a ceiling and a floor together

    the line:
    B∈Θ(n log⁡2 n)B \in \Theta(n \,\log_2\, n)

    why it is allowed: Lines 28 and 29, the same growth.

try it with a small nn: at n=8n = 8, line 1 gives B=11B = 11, which you can work out by hand

Why does a row already in order need no move?
  1. the move: what in order means

    the line:
    in a row in order, no numberstands before a smaller one\begin{gathered} \text{in a row in order, no number} \\ \text{stands before a smaller one} \end{gathered}

    why it is allowed: Each number is at most every number after it.

  2. the move: no number a gap to the left is bigger

    the line:
    on a row in order, no comparisonfinds the left number bigger\begin{gathered} \text{on a row in order, no comparison} \\ \text{finds the left number bigger} \end{gathered}

    why it is allowed: By line 1, so nothing moves, and the row stays in order.

  3. the move: count the moves

    the line:
    Z=0Z = 0

    why it is allowed: ZZ is the moves on a row in order. A move follows only a comparison finding the left number bigger.

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

Why does no row take more than (n−1)n2\frac{(n - 1)n}{2} moves, so that a shuffled row's average does not either?
  1. the move: what a move does

    the line:
    each comparison that finds theleft number bigger, and only sucha comparison, is followed by onemove: it trades that number awith a smaller b,h places to its right\begin{gathered} \text{each comparison that finds the} \\ \text{left number bigger, and only such} \\ \text{a comparison, is followed by one} \\ \text{move: it trades that number } a \\ \text{with a smaller } b \text{,} \\ h \text{ places to its right} \end{gathered}

    why it is allowed: Nothing else moves a number. On 8, 1, 5, 9, 3 the 8 and the 3 trade, 4 places apart.

  2. the move: the pair itself

    the line:
    the pair a,b is wrong beforeand right after\begin{gathered} \text{the pair } a, b \text{ is wrong before} \\ \text{and right after} \end{gathered}

    why it is allowed: Before, the bigger stands first; after, the smaller.

  3. the move: a number standing between them

    the line:
    a number c standingbetween them is in no morewrong pairs with a and bafter the move than before it\begin{gathered} \text{a number } c \text{ standing} \\ \text{between them is in no more} \\ \text{wrong pairs with } a \text{ and } b \\ \text{after the move than before it} \end{gathered}
    cc iswrong pairs with aa and bb before, standing aa, cc, bbafter, standing bb, cc, aa
    smaller than bb11
    equal to bb10
    bigger than bb, smaller than aa20
    equal to aa10
    bigger than aa11
    cc stands between the two that trade. Its wrong pairs with them never grow; in the first and last rows the move mends one and makes one.

    why it is allowed: Before, cc has aa on its left and bb on its right; after, the reverse. A pair is wrong when its bigger number stands first, and equal numbers never are.

  4. the move: every other pair

    the line:
    every other pairkeeps its order\begin{gathered} \text{every other pair} \\ \text{keeps its order} \end{gathered}

    why it is allowed: Only aa and bb move, and a number outside both stays on the same side of each.

  5. the move: add it up

    the line:
    each move leaves at leastone wrong pair fewer\begin{gathered} \text{each move leaves at least} \\ \text{one wrong pair fewer} \end{gathered}
    81593start5 wrong pairs31598move 12 wrong pairs13598move 21 wrong pair13589move 3no wrong pairsa wrong pair, bigger before smallerjust swappedthe pairs it mendeda pair it made
    8, 1, 5, 9, 3, move by move. Move 1 jumps 4 places and takes the wrong pairs from 5 to 2. Moves 2 and 3 take one each.

    why it is allowed: The pair mends, by line 2, and lines 3 and 4 add nothing to the count. On 8, 1, 5, 9, 3 only the 5 lies between the 8 and the 3 in size, so 5 wrong pairs become 2.

  6. the move: the sort ends in order

    the line:
    the sort ends withno wrong pair\begin{gathered} \text{the sort ends with} \\ \text{no wrong pair} \end{gathered}

    why it is allowed: The last pass, gap 1 by the first ladder's line 2, is insertion sort. It carries each number left past every bigger one before it, so the front stays in order, one number longer each time. On 7, 31, 42, 12, the 12 passes 42 and 31.

  7. the move: so the moves are at most the wrong pairs

    the line:
    on any row, the movesare at most the wrong pairsit starts with\begin{gathered} \text{on any row, the moves} \\ \text{are at most the wrong pairs} \\ \text{it starts with} \end{gathered}

    why it is allowed: By lines 5 and 6. On 8, 1, 5, 9, 3: 3 moves against 5 wrong pairs.

  8. the move: with the gap 1

    the line:
    with the gap 1, each move takesaway exactly one wrong pair\begin{gathered} \text{with the gap 1, each move takes} \\ \text{away exactly one wrong pair} \end{gathered}

    why it is allowed: Neighbours have no number between, so by lines 2 and 4 exactly one pair mends.

  9. the move: insertion sort's moves

    the line:
    insertion sort makes exactly onemove for each wrong pair\begin{gathered} \text{insertion sort makes exactly one} \\ \text{move for each wrong pair} \end{gathered}

    why it is allowed: By lines 6 and 8, insertion sort being the gap 1 pass alone. On 8, 1, 5, 9, 3: 5 moves.

  10. the move: never more than insertion sort

    the line:
    Shell sort never makesmore moves than insertionsort on the same row\begin{gathered} \text{Shell sort never makes} \\ \text{more moves than insertion} \\ \text{sort on the same row} \end{gathered}

    why it is allowed: By lines 7 and 9.

  11. the move: count the pairs

    the line:
    n numbers make1+⋯+(n−1) pairs\begin{gathered} n \text{ numbers make} \\ 1 + \dots + (n - 1) \text{ pairs} \end{gathered}
    54321back to front10 wrong pairsa wrong pair, bigger before smaller
    5, 4, 3, 2, 1, an arc over each wrong pair. All 10 of its pairs are wrong.

    why it is allowed: Count each pair at its second number, which pairs with each number before it. For 5 numbers, 1 + 2 + 3 + 4, which makes 10.

  12. the move: no more moves than pairs

    the line:
    on any row, the moves areat most 1+⋯+(n−1)\begin{gathered} \text{on any row, the moves are} \\ \text{at most } 1 + \dots + (n - 1) \end{gathered}

    why it is allowed: By lines 7 and 11, every wrong pair being a pair.

  13. the move: average over every shuffle

    the line:
    M≤1+⋯+(n−1)M \le 1 + \dots + (n - 1)

    why it is allowed: MM is the average moves over every shuffle of nn different numbers, with no formula known. No shuffle makes more, by line 12, so neither does their average.

  14. the move: use the page on adding up, its last number here being n - 1

    the line:
    M≤(n−1)((n−1)+1)2M \le \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 13'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 5 numbers, 4 times 5, halved, is 10.

  15. the move: tidy the bracket

    the line:
    M≤(n−1)n2M \le \frac{(n - 1)n}{2}

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

  16. the move: use the page on adding up, for one row

    the line:
    on any row, the movesare at most(n−1)((n−1)+1)2\begin{gathered} \text{on any row, the moves} \\ \text{are at most} \\ \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2} \end{gathered}

    why it is allowed: Line 12, summed as at line 14.

  17. the move: tidy the bracket, for one row

    the line:
    on any row, the movesare at most (n−1)n2\begin{gathered} \text{on any row, the moves} \\ \text{are at most } \frac{(n - 1)n}{2} \end{gathered}

    why it is allowed: As at line 15. For 5 numbers, at most 10.

  18. the move: a fact for a simpler ceiling

    the line:
    n−1≤nn - 1 \le n

    why it is allowed: Taking 1 away leaves less.

  19. the move: multiply both sides by n

    the line:
    (n−1)n≤n2(n - 1)n \le n^2

    why it is allowed: Line 18 times nn, above zero.

  20. the move: halve both sides

    the line:
    (n−1)n2≤n22\frac{(n - 1)n}{2} \le \frac{n^2}{2}

    why it is allowed: Line 19 halved. For 5 numbers, 10 is at most 12.5.

  21. the move: a simpler ceiling

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

    why it is allowed: By lines 15 and 20.

  22. the move: read it as a bound

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

    why it is allowed: By line 21, under half of n2n^2. On this site's 20 shuffles of 1,000 numbers it averaged about 8,968, far under 499,500.

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

What ceiling holds for the comparisons on any row, and what floor and ceiling for a shuffled row's average and for a dearest row?
  1. the move: what a comparison leads to

    the line:
    each comparison is followedby a move, or the numberpicked up stays put\begin{gathered} \text{each comparison is followed} \\ \text{by a move, or the number} \\ \text{picked up stays put} \end{gathered}

    why it is allowed: A comparison asks if the number hh places to the left is bigger. If so, a move follows, by the fourth ladder's line 1.

  2. the move: the comparisons followed by no move

    the line:
    in the pass with gap h,at most n−h comparisonsare followed by no move\begin{gathered} \text{in the pass with gap } h \text{,} \\ \text{at most } n - h \text{ comparisons} \\ \text{are followed by no move} \end{gathered}

    why it is allowed: On any row the pass picks up n−hn - h numbers. Each stops after one comparison with no move, or none if no number stands hh places to its left.

  3. the move: two kinds of comparison

    the line:
    the comparisons are thosefollowed by a move, andthose followed by none\begin{gathered} \text{the comparisons are those} \\ \text{followed by a move, and} \\ \text{those followed by none} \end{gathered}

    why it is allowed: By line 1.

  4. the move: count the first kind

    the line:
    those followed by a moveare as many as the moves\begin{gathered} \text{those followed by a move} \\ \text{are as many as the moves} \end{gathered}

    why it is allowed: By the fourth ladder's line 1.

  5. the move: add up the second kind

    the line:
    those followed by noneare at most B\begin{gathered} \text{those followed by none} \\ \text{are at most } B \end{gathered}

    why it is allowed: By line 2, summed over the gaps below nn, which the first ladder's line 3 adds up to BB.

  6. the move: put the two kinds together

    the line:
    on any row, the comparisons areat most the moves, plus B\begin{gathered} \text{on any row, the comparisons are} \\ \text{at most the moves, plus } B \end{gathered}
    passcomparisons followed by a movefollowed by nonen−hn - h
    gap 4134
    gap 1867
    in all9911
    42, 7, 31, 18, 56, 23, 12, 49, pass by pass. The comparisons followed by none stay at or under n−hn - h.

    why it is allowed: By lines 3 to 5. In section 1's run, 9 with a move and 9 without; 9 is at most 11.

  7. the move: put in the moves' ceiling

    the line:
    on any row, the comparisons areat most (n−1)n2, plus B\begin{gathered} \text{on any row, the comparisons are} \\ \text{at most } \frac{(n - 1)n}{2} \text{, plus } B \end{gathered}

    why it is allowed: By line 6 above and the fourth ladder's line 17. For 5 numbers, 10 plus 5.

  8. the move: count the gaps once more

    the line:
    G≤n−1G \le n - 1

    why it is allowed: The gaps grow, by the first ladder's line 8, so the GG gaps below nn are different whole numbers from 1 to n−1n - 1.

  9. the move: multiply both sides by n

    the line:
    G×n≤(n−1)nG \times n \le (n - 1)n

    why it is allowed: Line 8 times nn, above zero.

  10. the move: a ceiling for the row in order's count

    the line:
    B≤(n−1)nB \le (n - 1)n

    why it is allowed: By the first ladder's line 7 and line 9 above. Any true ceiling serves. For 5 numbers, 5 is at most 20.

  11. the move: put it in

    the line:
    on any row, the comparisons areat most (n−1)n2, plus (n−1)n\begin{gathered} \text{on any row, the comparisons are} \\ \text{at most } \frac{(n - 1)n}{2} \text{, plus } (n - 1)n \end{gathered}

    why it is allowed: By lines 7 and 10. For 5 numbers, 10 plus 20.

  12. the move: add the two parts

    the line:
    on any row, the comparisonsare at most 3(n−1)n2\begin{gathered} \text{on any row, the comparisons} \\ \text{are at most } \frac{3(n - 1)n}{2} \end{gathered}

    why it is allowed: (n−1)n(n - 1)n is two halves of itself; with the half before, three halves. No row costs more. For 5 numbers, 20 + 10 = 30.

  13. the move: a floor from the row in order

    the line:
    A≥(n−1)+(n−4)+(n−13)+…A \ge (n - 1) + (n - 4) + (n - 13) + \dots

    why it is allowed: AA is the average comparisons over every shuffle of nn different numbers, with no formula known. No row costs fewer, by the first ladder's line 4, so neither does the average.

  14. the move: the second ladder's floor

    the line:
    A≥n log⁡2 n8 for n≥4A \ge \frac{n \,\log_2\, n}{8} \text{ for } n \ge 4

    why it is allowed: By line 13 and the second ladder's line 27. For 5 numbers, the log to base 2 of 5 is about 2.32, an eighth of 5 times that is about 1.45, and all 120 orders average about 7.72.

  15. the move: read it as a bound

    the line:
    A∈Ω(n log⁡2 n)A \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 14, from 4 numbers on.

  16. the move: average over every shuffle

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

    why it is allowed: By line 12, an average never being more than its largest. For 5 numbers, about 7.72 is at most 30.

  17. the move: take three halves of both sides

    the line:
    3(n−1)n2≤3n22\frac{3(n - 1)n}{2} \le \frac{3n^2}{2}

    why it is allowed: The fourth ladder's line 19, times three halves.

  18. the move: a simpler ceiling

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

    why it is allowed: By lines 16 and 17.

  19. the move: read it as a bound

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

    why it is allowed: By line 18, under one and a half times n2n^2.

  20. the move: a dearest row is a row

    the line:
    a dearest row costs at least Band at most 3(n−1)n2\begin{gathered} \text{a dearest row costs at least } B \\ \text{and at most } \frac{3(n - 1)n}{2} \end{gathered}

    why it is allowed: A dearest row is still a row, so the first ladder's line 4 and line 12 above hold. For 8 numbers, 26, between 11 and 84.

  21. the move: the second ladder's floor, for a dearest row

    the line:
    a dearest row costs at leastn log⁡2 n8 from 4 numbers on\begin{gathered} \text{a dearest row costs at least} \\ \frac{n \,\log_2\, n}{8} \text{ from 4 numbers on} \end{gathered}

    why it is allowed: By line 20 and the second ladder's line 27. For 8 numbers, 26 is at least 3.

  22. the move: read it as a bound

    the line:
    a dearest row’s cost is Ω(n log⁡2 n)\text{a dearest row's cost is } \Omega(n \,\log_2\, n)

    why it is allowed: By line 21.

  23. the move: a simpler ceiling, for a dearest row

    the line:
    a dearest row costsat most 3n22\begin{gathered} \text{a dearest row costs} \\ \text{at most } \frac{3n^2}{2} \end{gathered}

    why it is allowed: By lines 20 and 17. For 8 numbers, 26 is at most 96.

  24. the move: read it as a bound

    the line:
    a dearest row’s cost is O(n2)\text{a dearest row's cost is } O(n^2)

    why it is allowed: By line 23. Research finds a tighter ceiling, by an argument beyond this page.

  25. the move: what is not known

    the line:
    how fast A growsis not known\begin{gathered} \text{how fast } A \text{ grows} \\ \text{is not known} \end{gathered}

    why it is allowed: The floors grow like n log⁡2 nn \,\log_2\, n and the ceilings like n2n^2, so no tight bound follows. Section 2's slope of about 1.2 is measured, not proved. At 1,000 numbers line 14's floor is about 1,246, line 16's ceiling 1,498,500, and the measured average about 13,991.

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

count it yourself

Follow every step on 7, 12, 18, 23, 31, 42, 49, 56 and check the comparisons against the first ladder, 7 + 4 = 11. Nothing moves.

7, 12, 18, 23, 31, 42, 49, 56, every step written down
stepthe rowwhat happenscomparisonsmoves
17, 12, 18, 23, 31, 42, 49, 56There are 8 numbers in a row. Sort the numbers 4 places apart first, then the neighbours.7, 12, 18, 23, 31, 42, 49, 5600
27, 12, 18, 23, 31, 42, 49, 56Compare numbers 4 places apart.7, 12, 18, 23, 31, 42, 49, 5600
37, 12, 18, 23, 31, 42, 49, 56Pick up 31 and carry it left in jumps of 4, past every bigger number.7, 12, 18, 23, 31, 42, 49, 5600
47, 12, 18, 23, 31, 42, 49, 567 is not bigger than 31, so 31 stops here.7, 12, 18, 23, 31, 42, 49, 5610
57, 12, 18, 23, 31, 42, 49, 56Pick up 42 and carry it left in jumps of 4, past every bigger number.7, 12, 18, 23, 31, 42, 49, 5610
67, 12, 18, 23, 31, 42, 49, 5612 is not bigger than 42, so 42 stops here.7, 12, 18, 23, 31, 42, 49, 5620
77, 12, 18, 23, 31, 42, 49, 56Pick up 49 and carry it left in jumps of 4, past every bigger number.7, 12, 18, 23, 31, 42, 49, 5620
87, 12, 18, 23, 31, 42, 49, 5618 is not bigger than 49, so 49 stops here.7, 12, 18, 23, 31, 42, 49, 5630
97, 12, 18, 23, 31, 42, 49, 56Pick up 56 and carry it left in jumps of 4, past every bigger number.7, 12, 18, 23, 31, 42, 49, 5630
107, 12, 18, 23, 31, 42, 49, 5623 is not bigger than 56, so 56 stops here.7, 12, 18, 23, 31, 42, 49, 5640
117, 12, 18, 23, 31, 42, 49, 56Now the last pass: compare neighbours, as plain insertion sort does.7, 12, 18, 23, 31, 42, 49, 5640
127, 12, 18, 23, 31, 42, 49, 56Pick up 12 and carry it left past every bigger neighbour.7, 12, 18, 23, 31, 42, 49, 5640
137, 12, 18, 23, 31, 42, 49, 567 is not bigger than 12, so 12 stops here.7, 12, 18, 23, 31, 42, 49, 5650
147, 12, 18, 23, 31, 42, 49, 56Pick up 18 and carry it left past every bigger neighbour.7, 12, 18, 23, 31, 42, 49, 5650
157, 12, 18, 23, 31, 42, 49, 5612 is not bigger than 18, so 18 stops here.7, 12, 18, 23, 31, 42, 49, 5660
167, 12, 18, 23, 31, 42, 49, 56Pick up 23 and carry it left past every bigger neighbour.7, 12, 18, 23, 31, 42, 49, 5660
177, 12, 18, 23, 31, 42, 49, 5618 is not bigger than 23, so 23 stops here.7, 12, 18, 23, 31, 42, 49, 5670
187, 12, 18, 23, 31, 42, 49, 56Pick up 31 and carry it left past every bigger neighbour.7, 12, 18, 23, 31, 42, 49, 5670
197, 12, 18, 23, 31, 42, 49, 5623 is not bigger than 31, so 31 stops here.7, 12, 18, 23, 31, 42, 49, 5680
207, 12, 18, 23, 31, 42, 49, 56Pick up 42 and carry it left past every bigger neighbour.7, 12, 18, 23, 31, 42, 49, 5680
217, 12, 18, 23, 31, 42, 49, 5631 is not bigger than 42, so 42 stops here.7, 12, 18, 23, 31, 42, 49, 5690
227, 12, 18, 23, 31, 42, 49, 56Pick up 49 and carry it left past every bigger neighbour.7, 12, 18, 23, 31, 42, 49, 5690
237, 12, 18, 23, 31, 42, 49, 5642 is not bigger than 49, so 49 stops here.7, 12, 18, 23, 31, 42, 49, 56100
247, 12, 18, 23, 31, 42, 49, 56Pick up 56 and carry it left past every bigger neighbour.7, 12, 18, 23, 31, 42, 49, 56100
257, 12, 18, 23, 31, 42, 49, 5649 is not bigger than 56, so 56 stops here.7, 12, 18, 23, 31, 42, 49, 56110
267, 12, 18, 23, 31, 42, 49, 56In order, after 11 comparisons and no moves.7, 12, 18, 23, 31, 42, 49, 56110

In all, 11 comparisons. The formula from section 4, (n−1)+(n−4)(n - 1) + (n - 4), gives B=11B = 11 at n=8n = 8: the same.

where you meet it

Shell sort is short and needs no room beyond the row. Where you meet it, and what is used instead.

  • inside the bzip2 compressor

    bzip2 makes files smaller. For each block of a file it sorts every reading of the block that starts at one of its places and wraps round. On a block of 10,000 places or more it groups the readings by their first letters. A group that is short, or still alike after many letters, it sorts with Shell sort and these gaps. Its table holds fourteen, 1, 4, 13, 40, 121, 364, 1,093, 3,280, 9,841, 29,524, 88,573, 265,720, 797,161 and 2,391,484.

    source: bzip2's code, blocksort.c (mainSimpleSort, BZ2_blockSort and the table of gaps), read from libbz2.so.1.0.4 as installed

  • a lesson in what long jumps are worth

    On the same 20 shuffles of 10,000 numbers, Shell sort averaged about 235,647 comparisons against insertion sort's about 25,045,660, about a hundredth.

    source: this site's measured runs of both sorts, 20 shuffles at each length

what is used instead

The ready-made sorts of Python, Java and C++ use no Shell sort, and each hands short stretches to a form of insertion sort.

how it compares

Shell sort beside the other ways to put a row in order. Its line on the plot is points only, as no formula for its average is known.

comparisons on a shuffled row, on the log-log scales of section 2, one line for each way whose page is written
102104106108101010121014101102103104105106107bubble sortcocktail shaker sortinsertion sortselection sortquick sortrandomised quick sortmerge sortheap sortshell sort10110210310410510610710810910101011101210131014101102103104105106107bubble sortcocktail shaker sortinsertion sortselection sortquick sortrandomised quick sortmerge sortheap sortshell 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