Skip to content

Cocktail shaker sort

ordering

Level 1 of 3

Also called Shaker sort and Bidirectional bubble sort.

how it works

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

Cocktail shaker sort puts a row of numbers in order, smallest first. It is bubble sort, which only walks right, with a walk back. A walk right compares each pair of neighbours and swaps them when the left one is bigger, carrying the biggest number to the right end. A walk left carries the smallest to the left end the same way. Each walk that swaps leaves one more number in place. The sort stops after a walk that swaps nothing, or when only one number is not yet in place. Equal neighbours never swap, so equal numbers keep their order, as the second picture shows.

32514start23145walk 14 pairs compared12345walk 23 pairs compared12345walk 32 pairs, no swapone walkin place for good
3, 2, 5, 1, 4, walk by walk.
2a32b1start2a2b13walk 112a2b3walk 212a2b3walk 3
The thick lines follow the two 2s, told apart as 2a and 2b. They are compared only in walk 3, and equal numbers do not swap, so 2a ends first.
afterthe rowcomparisons
the start12, 18, 23, 31, 42, 49, 56, 7
walk 1, right12, 18, 23, 31, 42, 49, 7, 567
walk 2, left7, 12, 18, 23, 31, 42, 49, 566
walk 3, right7, 12, 18, 23, 31, 42, 49, 565
The run below. Walk 2 carries the 7 to the front at once, so 7 + 6 + 5 = 18 comparisons. Bubble sort moves the 7 one place a walk, so all 7 walks run, 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28.
A small one at the back: 8 moments of its 30 steps, the steps between them left for the watch page
  1. step 2 of 30

    121823314249567

    12 is not bigger than 18, so they stay as they are.

    what it remembers to know where it is
    walk number
    1
    pair starting at position
    1
    swapped on this walk
    no

    watch from here

  2. step 8 of 30

    121823314249567

    56 is bigger than 7, so they are the wrong way round.

    what it remembers to know where it is
    walk number
    1
    pair starting at position
    7
    swapped on this walk
    no

    watch from here

  3. step 10 of 30

    121823314249756

    56 is now at the right end of the unsorted part. Nothing bigger is left, so it stays there for good.

    what it remembers to know where it is
    walk number
    1
    pair starting at position
    not yet
    swapped on this walk
    yes

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

    watch from here

  4. step 12 of 30

    121823314274956

    Swap them: 7 moves left and 49 moves right.

    what it remembers to know where it is
    walk number
    2
    pair starting at position
    6
    swapped on this walk
    yes

    watch from here

  5. step 22 of 30

    712182331424956

    Swap them: 7 moves left and 12 moves right.

    what it remembers to know where it is
    walk number
    2
    pair starting at position
    1
    swapped on this walk
    yes

    watch from here

  6. step 23 of 30

    712182331424956

    7 is now at the left end of the unsorted part. Nothing smaller is left, so it stays there for good.

    what it remembers to know where it is
    walk number
    2
    pair starting at position
    not yet
    swapped on this walk
    yes

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

    watch from here

  7. step 29 of 30

    712182331424956

    That walk swapped nothing, so everything left is already in order.

    what it remembers to know where it is
    walk number
    3
    pair starting at position
    not yet
    swapped on this walk
    no

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

    watch from here

  8. step 30 of 30

    712182331424956

    In order, after 18 comparisons and 7 swaps.

    what it remembers to know where it is
    walk number
    3
    pair starting at position
    not yet
    swapped on this walk
    no

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

    watch from here

the steps, in plain words
  1. repeatPython lines 11 and 12
  2. walk right along the unsorted part, one neighbouring pair at a timePython line 13
  3. if the left one is bigger than the right onePython line 14
  4. swap themPython lines 15 and 16
  5. the right end of the unsorted part is now in placePython line 19
  6. walk left along the unsorted part, one neighbouring pair at a timePython lines 20 and 21
  7. if the left one is bigger than the right onePython line 22
  8. swap themPython lines 23 and 24
  9. the left end of the unsorted part is now in placePython line 27
  10. until a walk swaps nothingPython lines 17, 18, 25 and 26
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 cocktail_shaker_sort(numbers):
    """Put a list of numbers in order, smallest first, in the list itself.

    Walk right along the part not yet in place, swapping each neighbouring
    pair that stands the wrong way round, so the biggest reaches the right
    end; then walk back left, so the smallest reaches the left end. The ends
    close in until a walk swaps nothing or one number is left. The list is
    sorted where it stands, with no copy made, and handed back.
    """
    low, high = 0, len(numbers) - 1  # the part not yet in place
    while low < high:  # repeat
        swapped = False
        for i in range(low, high):  # walk right, pair by pair
            if numbers[i] > numbers[i + 1]:
                numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]  # swap them
                swapped = True
        if not swapped:  # a walk that swaps nothing: the rest is in order
            break
        high -= 1  # the right end is now in place
        swapped = False
        for i in range(high - 1, low - 1, -1):  # walk left, pair by pair
            if numbers[i] > numbers[i + 1]:
                numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]  # swap them
                swapped = True
        if not swapped:  # a walk that swaps nothing: the rest is in order
            break
        low += 1  # the left end is now in place
    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 of different numbers back to front climbs about two steps for each step across, 45 comparisons at 10 numbers and 4,950 at 100. A row in order climbs one step, 9 at 10 numbers and 99 at 100. The shuffled points, each the mean of 20 shuffles, lie close under the top line.

comparisons, ten times more at each mark up

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

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

  • different numbers 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 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, the cheapest rowsolid 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 cocktail shaker 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 cocktail_shaker_sort(numbers):
    """Put a list of numbers in order, smallest first, in the list itself.

    Walk right along the part not yet in place, swapping each neighbouring
    pair that stands the wrong way round, so the biggest reaches the right
    end; then walk back left, so the smallest reaches the left end. The ends
    close in until a walk swaps nothing or one number is left. The list is
    sorted where it stands, with no copy made, and handed back.
    """
    low, high = 0, len(numbers) - 1  # the part not yet in place
    while low < high:  # repeat
        swapped = False
        for i in range(low, high):  # walk right, pair by pair
            if numbers[i] > numbers[i + 1]:
                numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]  # swap them
                swapped = True
        if not swapped:  # a walk that swaps nothing: the rest is in order
            break
        high -= 1  # the right end is now in place
        swapped = False
        for i in range(high - 1, low - 1, -1):  # walk left, pair by pair
            if numbers[i] > numbers[i + 1]:
                numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]  # swap them
                swapped = True
        if not swapped:  # a walk that swaps nothing: the rest is in order
            break
        low += 1  # the left end is now in place
    return numbers


def count(row):
    """How many comparisons cocktail shaker sort makes on this row."""
    Counted.comparisons = 0
    cocktail_shaker_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, walk 1 swaps nothing and the sort stops. Different numbers back to front make every walk swap. Each swap mends one wrong pair.

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

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

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestalready in order, the cheapest rowaverageshuffled, different numbers in a random order, every order as likelyworstdifferent numbers back to front, one of the dearest rows
comparisonsn−1n - 1between n(n−1)4\frac{n(n - 1)}{4} and n(n−1)2\frac{n(n - 1)}{2}n(n−1)2\frac{n(n - 1)}{2}
swapsnonen(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: a few spare places, the same however long the row

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

row of 5comparisonsswaps
1, 2, 3, 4, 540
all 120 orders, on averageabout 9.145
5, 4, 3, 2, 11010
In order, one walk of 4 comparisons. Back to front, 4 + 3 + 2 + 1 = 10 comparisons and 10 swaps. 5 numbers have 5 × 4 × 3 × 2 × 1 = 120 orders, 5 choices for place 1, then 4, and on. They average 5 swaps, the grid's n(n−1)4\frac{n(n - 1)}{4} at 5.
row of 5cocktail shaker sortbubble sort
1, 4, 5, 2, 3109
all 120 orders, on averageabout 9.14about 9.26
Comparisons on rows of 5. On 1, 4, 5, 2, 3 it takes 4 walks, bubble sort 3. Of all 120 orders, cocktail shaker sort is cheaper on 24, dearer on 10 and the same on the other 86.
14523start14235walk 14 pairs compared12435walk 23 pairs compared12345walk 32 pairs compared12345walk 41 pair, no swapone walkin place for good
1, 4, 5, 2, 3, walk by walk.

where the formula comes from

Each count in section 3, in small steps. The average comparisons get a floor and a ceiling instead.

Why does a row of different numbers back to front take n(n−1)2\frac{n(n - 1)}{2} comparisons, the most any row can?
  1. the move: count the numbers walk k looks at

    the line:
    after k−1 walks, walk klooks at n−(k−1) numbers\begin{gathered} \text{after } k - 1 \text{ walks, walk } k \\ \text{looks at } n - (k - 1) \text{ numbers} \end{gathered}

    why it is allowed: Each earlier walk swapped, or the sort would have stopped, and left one more number at an end. For walk 2 of 5 numbers, 5 less 1.

  2. the move: open the bracket

    the line:
    walk k looks atn−k+1 numbers\begin{gathered} \text{walk } k \text{ looks at} \\ n - k + 1 \text{ numbers} \end{gathered}

    why it is allowed: Take away kk, then give 1 back. For walk 2 of 5 numbers, 5 less 2, plus 1, is 4.

  3. the move: count the pairs among them

    the line:
    so walk k comparesn−k neighbouring pairs\begin{gathered} \text{so walk } k \text{ compares} \\ n - k \text{ neighbouring pairs} \end{gathered}

    why it is allowed: Neighbouring pairs are one fewer than the numbers. 4 numbers make 3 pairs.

  4. the move: count the walks

    the line:
    there are at most n−1 walks\text{there are at most } n - 1 \text{ walks}

    why it is allowed: With n−1n - 1 for kk, line 3 gives 1 pair, then one number is left. For 5 numbers, walk 4 looks at 2 numbers, 1 pair. The sort may stop sooner, after a walk that swaps nothing.

  5. the move: no row costs more

    the line:
    no row of n numberscosts more than(n−1)+⋯+1\begin{gathered} \text{no row of } n \text{ numbers} \\ \text{costs more than} \\ (n - 1) + \dots + 1 \end{gathered}
    54321start43215walk 14 pairs compared14325walk 23 pairs compared13245walk 32 pairs compared12345walk 41 pair comparedone walkin place for good
    5, 4, 3, 2, 1, walk by walk.

    why it is allowed: By lines 3 and 4, any row runs at most walks 1 to n−1n - 1, walk kk comparing n−kn - k pairs. For 5 numbers, at most 4 + 3 + 2 + 1, as drawn.

  6. the move: see why this row never stops early

    the line:
    on a row back to front,every walk swaps\begin{gathered} \text{on a row back to front,} \\ \text{every walk swaps} \end{gathered}

    why it is allowed: With different numbers back to front, every pair of neighbours is wrong. Each walk carries the biggest or smallest still unplaced to its end, each swap passing it over one number. So the part between stays back to front, one shorter: in line 5's picture 4, 3, 2, 1 after walk 1, then 4, 3, 2. So every walk swaps, and all n−1n - 1 run.

  7. the move: add up the walks

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

    why it is allowed: CC is the comparisons on this row. By lines 6 and 3 all walks run, comparing n−1n - 1, then one fewer, down to 1. For 4 numbers, 3 + 2 + 1.

  8. 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 line 5 no row costs more, and by line 7 this row costs just that. It is one of the dearest, not the only one. 2, 3, 1 costs 3, as 3, 2, 1 does.

  9. the move: add them the other way round

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

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

  10. the move: use the page on adding up, its last number here being 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: The box above shows 1 + 2 + ... + 5 is 5 times 6, halved, and so for any last number. For 4 numbers, 3 times 4, halved, is 6.

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

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

  13. the move: multiply out the bracket

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

    why it is allowed: nn lots of nn, less nn lots of 1. For 4 numbers, 4 times 3 is 16 less 4.

  14. 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. For 4 numbers, 12 halved is 8 less 2.

  15. the move: a ceiling

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

    why it is allowed: Line 14 takes n2\frac{n}{2}, above zero, from n22\frac{n^2}{2}. For 4 numbers, 6 is at most 8.

  16. the move: read it as a bound

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

    why it is allowed: By line 15, CC stays under half of n2n^2.

  17. 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: Now a floor, for line 20. Half of nn is at least 1 from 2 numbers on. At 2 numbers, 1 is at most 1.

  18. the move: multiply both sides by n

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

    why it is allowed: Line 17 times nn, above zero, so the order holds. For 10 numbers, 10 is at most 50.

  19. the move: halve both sides

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

    why it is allowed: Line 18 halved. For 10 numbers, 5 is at most 25.

  20. 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
    nnthe first quarterthe second, less n2\frac{n}{2}CC
    2101
    4426
    10252045
    1002,5002,4504,950
    Half of n squared as two quarters, the second less half of n. At 10 numbers, 25 plus 20 is 45.

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

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

  22. the move: read it as a bound

    the line:
    C∈Ω(n2)C \in \Omega(n^2)
    10210410610810101012101410110210310410510610710110210310410510610710810910101011101210131014101102103104105106107
    • C=n(n−1)2C = \frac{n(n - 1)}{2}
    • n22\frac{n^2}{2}
    • n24\frac{n^2}{4}
    CC runs between the other two, all three about two steps up for each step across.

    why it is allowed: By line 21, from 2 numbers on. At 1 number CC is 0, but a floor need only hold for rows long enough.

  23. the move: a ceiling and a floor together

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

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

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

Why does a row already in order take 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
    row of 5walk 1 comparesthen
    1, 2, 3, 4, 54swaps none, stops
    3, 2, 5, 1, 44swaps, walks on
    5, 4, 3, 2, 14swaps, walks on
    Walk 1 compares all 4 pairs of any row of 5. Only a row in order swaps none and stops at 4.

    why it is allowed: Walk 1 runs over the whole row, so by the first ladder's line 3 it compares all n−1n - 1 pairs.

  2. the move: walk once

    the line:
    B=n−1B = n - 1
    12345start12345walk 14 pairs, no swapone walkin place for good
    1, 2, 3, 4, 5, walk by walk.

    why it is allowed: BB is the comparisons on a row in order. No pair is wrong, so walk 1 swaps nothing and ends the sort.

  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 line 1 no row costs less, and by line 2 this row costs just that.

  4. the move: a ceiling

    the line:
    B≤nB \le n

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

  5. the move: read it as a bound

    the line:
    B∈O(n)B \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 from 2 numbers on.

  7. the move: a floor

    the line:
    B≥n−n2 for n≥2B \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:
    B≥n2 for n≥2B \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:
    B∈Ω(n)B \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:
    B∈Θ(n)B \in \Theta(n)

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

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

How many swaps does a shuffled row of different numbers take, on average?
  1. the move: a swap mends one wrong pair

    the line:
    each swap mends one wrong pairand makes no new one\begin{gathered} \text{each swap mends one wrong pair} \\ \text{and makes no new one} \end{gathered}
    2641start4 wrong pairs2461swap 13 wrong pairs2416swap 22 wrong pairs2146swap 31 wrong pair1246swap 4no wrong pairsa wrong pair, bigger before smallerjust swappedthe pair it mended
    2, 6, 4, 1, swap by swap.

    why it is allowed: The sort swaps only wrong neighbours, so each swap mends its pair. Every other number stands before both or after both, so its pairs with them stay as they were. At swap 1 the 2 stands before both and the 1 after both, so their arcs stay; only the dashed one goes.

  2. the move: count the swaps as wrong pairs

    the line:
    as many swaps as wrong pairsat the start\begin{gathered} \text{as many swaps as wrong pairs} \\ \text{at the start} \end{gathered}

    why it is allowed: 2, 6, 4, 1 has 4 wrong pairs, 2 and 1, 6 and 4, 6 and 1, 4 and 1. Each swap mends one, and the sort ends in order, so 4 swaps.

  3. the move: average pair by pair

    the line:
    the average swaps: add up,for each pair, the shareof shuffles in whichthat pair stands wrong\begin{gathered} \text{the average swaps: add up,} \\ \text{for each pair, the share} \\ \text{of shuffles in which} \\ \text{that pair stands wrong} \end{gathered}
    shufflethe numbers 1 and 2the numbers 1 and 3the numbers 2 and 3swaps
    1, 2, 30000
    1, 3, 20011
    2, 1, 31001
    2, 3, 11102
    3, 1, 20112
    3, 2, 11113
    in all3339
    average3 over 63 over 63 over 69 over 6
    Each pair's tally on every shuffle of 1, 2 and 3.

    why it is allowed: Tally each pair on each shuffle, 1 when wrong. By line 2 each line of the grid adds up to that shuffle's swaps. Total by lines or by columns, the same 9. Divided by the 6 shuffles, the average swaps are the pairs' shares added up. For 3 numbers, 3 over 6 plus 3 over 6 plus 3 over 6 is 9 over 6.

  4. 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}
    the pair 1 and 2 wrongtraded, the pair right
    2, 1, 31, 2, 3
    2, 3, 11, 3, 2
    3, 2, 13, 1, 2
    Each shuffle with the pair 1 and 2 wrong, beside its trade.

    why it is allowed: Trading the 1 and the 2 turns each shuffle with that pair wrong into one with it right, and back. So the pair is wrong in exactly half, as for any pair of different numbers and any nn.

  5. the move: count the pairs

    the line:
    n numbers make(n−1)+⋯+1 pairs,neighbours or not\begin{gathered} n \text{ numbers make} \\ (n - 1) + \dots + 1 \text{ pairs,} \\ \text{neighbours or not} \end{gathered}

    why it is allowed: The first number pairs with the n−1n - 1 after it, the next with one fewer, down to the last two. For 3 numbers, 2 + 1.

  6. the move: add up the halves

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

    why it is allowed: EE is the average swaps over every shuffle of nn different numbers. By lines 3 to 5, a half for each pair. For 3 numbers, three halves.

  7. the move: put in the first ladder's sum

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

    why it is allowed: By the first ladder's lines 7 to 12, (n−1)+⋯+1(n - 1) + \dots + 1 is n(n−1)2\frac{n(n - 1)}{2}.

  8. the move: multiply the fractions

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

    why it is allowed: Half of a half is a quarter. For 3 numbers, 1.5, line 3's 9 over 6.

  9. the move: multiply out the bracket

    the line:
    E=n2−n4E = \frac{n^2 - n}{4}

    why it is allowed: nn lots of nn, less nn lots of 1. For 3 numbers, 9 less 3, over 4, is 1.5.

  10. the move: take a quarter of each part

    the line:
    E=n24−n4E = \frac{n^2}{4} - \frac{n}{4}

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

  11. the move: a ceiling

    the line:
    E≤n24E \le \frac{n^2}{4}

    why it is allowed: Line 10 takes n4\frac{n}{4}, above zero, from n24\frac{n^2}{4}.

  12. the move: read it as a bound

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

    why it is allowed: By line 11.

  13. the move: split off a quarter of n

    the line:
    E=n4×(n−1)E = \frac{n}{4} \times (n - 1)

    why it is allowed: Now a floor. Line 8 is a quarter of nn times n−1n - 1; lines 14 to 19 replace n−1n - 1 with half of nn, no bigger, so EE stays at least that. For 10 numbers, 2.5 times 9 is 22.5.

  14. the move: a fact for the floor

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

    why it is allowed: Half of nn is at least 1 from 2 numbers on.

  15. the move: take both sides away from n

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

    why it is allowed: By line 14, 1 is at most half of nn, so nn less 1 is at least nn less half of nn. For 10 numbers, 9 is at least 10 less 5.

  16. the move: tidy the fact

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

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

  17. the move: multiply both sides by a quarter of n

    the line:
    n4×(n−1)≥n4×n2 for n≥2\frac{n}{4} \times (n - 1) \ge \frac{n}{4} \times \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: Line 16 times a quarter of nn, above zero, so the order holds. For 10 numbers, 22.5 is at least 12.5.

  18. the move: a floor

    the line:
    E≥n4×n2 for n≥2E \ge \frac{n}{4} \times \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: By line 13, EE is the left side of line 17.

  19. the move: tidy the floor

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

    why it is allowed: A quarter of nn times half of nn is an eighth of nn times nn.

  20. the move: read it as a bound

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

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

  21. the move: a ceiling and a floor together

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

    why it is allowed: Lines 20 and 12 bound EE by the same growth, n2n^2.

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

Between which floor and ceiling do a shuffled row's comparisons lie, on average?
  1. the move: a floor from the swaps

    the line:
    A≥n(n−1)4A \ge \frac{n(n - 1)}{4}
    shuffleswapscomparisons
    1, 2, 302
    1, 3, 213
    2, 1, 313
    2, 3, 123
    3, 1, 223
    3, 2, 133
    in all917
    average1.5about 2.83
    Every shuffle of 1, 2 and 3 makes at least as many comparisons as swaps, and at most 3. So do the averages.

    why it is allowed: AA is the average comparisons over every shuffle of nn different numbers, which section 2 estimates by the mean of 20 shuffles. Each swap follows a comparison, so AA is at least the average swaps, line 8 of the ladder on average swaps.

  2. 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: Lines 13 to 19 of the ladder on average swaps show n(n−1)4\frac{n(n - 1)}{4} is at least n28\frac{n^2}{8}. For 10 numbers, 22.5 is at least 12.5.

  3. the move: read it as a bound

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

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

  4. the move: a ceiling from the dearest rows

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

    why it is allowed: By the first ladder's lines 5 and 7 to 12, no row costs more, so neither does the average.

  5. the move: a simpler ceiling

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

    why it is allowed: By the first ladder's lines 12 to 15, n(n−1)2\frac{n(n - 1)}{2} is at most n22\frac{n^2}{2}.

  6. the move: read it as a bound

    the line:
    A∈O(n2)A \in O(n^2)
    10210410610810101012101410110210310410510610710110210310410510610710810910101011101210131014101102103104105106107
    • line 4, n(n−1)2\frac{n(n - 1)}{2}
    • line 1, n(n−1)4\frac{n(n - 1)}{4}
    Line 4's ceiling and line 1's floor. By those lines, AA lies between them.

    why it is allowed: By line 5.

  7. the move: a ceiling and a floor together

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

    why it is allowed: Lines 3 and 6 bound AA by the same growth, n2n^2. At 1,000 numbers the mean of 20 shuffles is about 378,751, between line 1's 249,750 and line 4's 499,500.

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

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

    the line:
    on a row back to front,every pair is wrong\begin{gathered} \text{on a row back to front,} \\ \text{every pair is wrong} \end{gathered}
    4321back to front6 wrong pairsa wrong pair, bigger before smaller
    4, 3, 2, 1 and its wrong pairs.

    why it is allowed: With different numbers back to front, each is bigger than the next, so bigger than every one after it. In 4, 3, 2, 1 all 6 pairs are wrong.

  2. the move: count the pairs

    the line:
    n numbers make(n−1)+⋯+1 pairs,neighbours or not\begin{gathered} n \text{ numbers make} \\ (n - 1) + \dots + 1 \text{ pairs,} \\ \text{neighbours or not} \end{gathered}

    why it is allowed: As line 5 of the ladder on average swaps counts them. For 4 numbers, 3 + 2 + 1.

  3. the move: count the swaps as wrong pairs

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

    why it is allowed: WW is the swaps on this row, its wrong pairs by line 2 of the ladder on average swaps, so every pair by line 1, counted by line 2.

  4. the move: no row makes more

    the line:
    no row of n numbersmakes more swaps\begin{gathered} \text{no row of } n \text{ numbers} \\ \text{makes more swaps} \end{gathered}

    why it is allowed: A row's swaps are its wrong pairs, and no row has more wrong pairs than pairs.

  5. the move: the first ladder's sum

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

    why it is allowed: By the first ladder's lines 7 to 12. For 4 numbers, 6.

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

Why does a row already in order need no swap?
  1. the move: no pair is wrong

    the line:
    a row in order hasno wrong pair\begin{gathered} \text{a row in order has} \\ \text{no wrong pair} \end{gathered}

    why it is allowed: In a row in order each number is at most every number after it.

  2. the move: count the swaps

    the line:
    Z=0Z = 0

    why it is allowed: ZZ is the swaps on a row in order, its wrong pairs by line 2 of the ladder on average swaps, so none.

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

What does a row of different numbers in order cost with its smallest moved last, as in 2, 4, 6, 8, 10, 1?
  1. the move: walk 1 swaps only the last pair

    the line:
    walk 1 compares n−1 pairsand swaps only the last\begin{gathered} \text{walk 1 compares } n - 1 \text{ pairs} \\ \text{and swaps only the last} \end{gathered}
    2468101start2468110walk 15 pairs compared1246810walk 24 pairs compared1246810walk 33 pairs, no swapone walkin place for good
    2, 4, 6, 8, 10, 1, walk by walk.

    why it is allowed: Take nn at least 3; line 5 says why. Every pair of neighbours is in order but the last, so walk 1 compares them all and swaps that one.

  2. the move: walk 2 carries the 1 to the front

    the line:
    walk 2 compares n−2 pairsand carries the 1 to the front\begin{gathered} \text{walk 2 compares } n - 2 \text{ pairs} \\ \text{and carries the 1 to the front} \end{gathered}
    aftercocktail shaker sortbubble sort
    the start2, 4, 6, 8, 10, 12, 4, 6, 8, 10, 1
    walk 12, 4, 6, 8, 1, 102, 4, 6, 8, 1, 10
    walk 21, 2, 4, 6, 8, 102, 4, 6, 1, 8, 10
    walk 31, 2, 4, 6, 8, 102, 4, 1, 6, 8, 10
    walk 4stopped2, 1, 4, 6, 8, 10
    walk 5stopped1, 2, 4, 6, 8, 10
    Cocktail shaker sort's walk 2 carries the 1 to the front, and walk 3 stops the sort. Bubble sort moves the 1 one place a walk, so all 5 walks run.

    why it is allowed: Walk 2 goes left from the 1, now at place n−1n - 1, over places 1 to n−1n - 1, so n−2n - 2 pairs. Each has the 1 just right of a bigger number, so each swaps, and the row is in order.

  3. the move: walk 3 swaps nothing

    the line:
    walk 3 compares n−3 pairsand swaps nothing\begin{gathered} \text{walk 3 compares } n - 3 \text{ pairs} \\ \text{and swaps nothing} \end{gathered}

    why it is allowed: Places 2 to n−1n - 1 make n−3n - 3 pairs, all in order, so the sort stops. For 6 numbers, places 2 to 5 hold 2, 4, 6 and 8, so 3 pairs. With 3 numbers walk 3 has no pair and adds 0.

  4. the move: add up the walks

    the line:
    L=(n−1)+(n−2)+(n−3)for n≥3\begin{gathered} L = (n - 1) + (n - 2) + (n - 3) \\ \text{for } n \ge 3 \end{gathered}

    why it is allowed: LL is the comparisons on this row, lines 1 to 3 added up. For 6 numbers, 5 + 4 + 3.

  5. the move: collect the terms

    the line:
    L=3n−6 for n≥3L = 3n - 6 \text{ for } n \ge 3

    why it is allowed: Three nns, less 1, 2 and 3. For 6 numbers, 18 less 6 is 12. At 2 numbers it gives 0, but 2, 1 takes 1 comparison.

  6. the move: a ceiling

    the line:
    L≤3n for n≥3L \le 3n \text{ for } n \ge 3

    why it is allowed: Taking 6 from three times nn leaves less.

  7. the move: read it as a bound

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

    why it is allowed: By line 6, from 3 numbers on.

  8. the move: a fact for the floor

    the line:
    6≤2n for n≥36 \le 2n \text{ for } n \ge 3

    why it is allowed: Twice nn is at least twice 3 from 3 numbers on. For 6 numbers, 6 is at most 12.

  9. the move: a floor

    the line:
    L≥3n−2n for n≥3L \ge 3n - 2n \text{ for } n \ge 3

    why it is allowed: Line 5 takes away 6, at most line 8's twice nn, and taking away more leaves less. For 6 numbers, 12 is at least 18 less 12.

  10. the move: tidy the floor

    the line:
    L≥n for n≥3L \ge n \text{ for } n \ge 3

    why it is allowed: Three times nn less twice nn is nn.

  11. the move: read it as a bound

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

    why it is allowed: By line 10, from 3 numbers on.

  12. the move: a ceiling and a floor together

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

    why it is allowed: Lines 11 and 7 bound LL by the same growth, nn.

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

count it yourself

Follow every step on 4, 3, 2, 1, then check the comparisons against n(n−1)2\frac{n(n - 1)}{2}. The swaps are 6 too.

4, 3, 2, 1, every step written down
stepthe rowwhat happenscomparisonsswaps
14, 3, 2, 1There are 4 numbers in a row. Walk right along it comparing each neighbouring pair, then walk back left the same way.4, 3, 2, 100
24, 3, 2, 14 is bigger than 3, so they are the wrong way round.4, 3, 2, 110
33, 4, 2, 1Swap them: 3 moves left and 4 moves right.3, 4, 2, 111
43, 4, 2, 14 is bigger than 2, so they are the wrong way round.3, 4, 2, 121
53, 2, 4, 1Swap them: 2 moves left and 4 moves right.3, 2, 4, 122
63, 2, 4, 14 is bigger than 1, so they are the wrong way round.3, 2, 4, 132
73, 2, 1, 4Swap them: 1 moves left and 4 moves right.3, 2, 1, 433
83, 2, 1, 44 is now at the right end of the unsorted part. Nothing bigger is left, so it stays there for good.3, 2, 1, 433
93, 2, 1, 42 is bigger than 1, so they are the wrong way round.3, 2, 1, 443
103, 1, 2, 4Swap them: 1 moves left and 2 moves right.3, 1, 2, 444
113, 1, 2, 43 is bigger than 1, so they are the wrong way round.3, 1, 2, 454
121, 3, 2, 4Swap them: 1 moves left and 3 moves right.1, 3, 2, 455
131, 3, 2, 41 is now at the left end of the unsorted part. Nothing smaller is left, so it stays there for good.1, 3, 2, 455
141, 3, 2, 43 is bigger than 2, so they are the wrong way round.1, 3, 2, 465
151, 2, 3, 4Swap them: 2 moves left and 3 moves right.1, 2, 3, 466
161, 2, 3, 43 is now at the right end of the unsorted part. Nothing bigger is left, so it stays there for good.1, 2, 3, 466
171, 2, 3, 4Only 2 is left, so it is in place too.1, 2, 3, 466
181, 2, 3, 4In order, after 6 comparisons and 6 swaps.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

Cocktail shaker sort is a lesson more than a tool. It shows what mending one weakness of bubble sort is worth.

  • a row in order with a new smallest number added at the back

    Add a number smaller than all the rest at the back of 99 numbers in order. Counted on this site, this sort's walk 2 carries it to the front, 294 comparisons in all, 3n−63n - 6 at its 100 numbers. Bubble sort moves it one place a walk, so all 99 walks run, 4,950.

    source: section 4's ladder on this row; this site's bubble sort on the same rows

  • a lesson in what a repair is worth

    The walk back mends bubble sort's slow small numbers, not its growth. On the same 20 shuffles of 1,000 numbers this sort averaged about 378,751 comparisons against bubble sort's 498,495, about a quarter fewer.

    source: section 4's ladders; this site's measured runs of bubble sort and cocktail shaker sort, 20 shuffles at each length

what is used instead

The ready-made sorts of Python, Java and C++ use no cocktail shaker sort. For short stretches they use a form of insertion sort. On every order of up to 8 different numbers, this site's insertion sort makes no more comparisons than its cocktail shaker sort.

how it compares

Cocktail shaker sort beside the other ways to put a row in order, on one plot and in one table.

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