Cocktail shaker 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.
| after | the row | comparisons |
|---|---|---|
| the start | 12, 18, 23, 31, 42, 49, 56, 7 | |
| walk 1, right | 12, 18, 23, 31, 42, 49, 7, 56 | 7 |
| walk 2, left | 7, 12, 18, 23, 31, 42, 49, 56 | 6 |
| walk 3, right | 7, 12, 18, 23, 31, 42, 49, 56 | 5 |
step 2 of 30
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
step 8 of 30
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
step 10 of 30
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.
step 12 of 30
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
step 22 of 30
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
step 23 of 30
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.
step 29 of 30
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.
step 30 of 30
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.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- repeatPython lines 11 and 12
- walk right along the unsorted part, one neighbouring pair at a timePython line 13
- if the left one is bigger than the right onePython line 14
- swap themPython lines 15 and 16
- the right end of the unsorted part is now in placePython line 19
- walk left along the unsorted part, one neighbouring pair at a timePython lines 20 and 21
- if the left one is bigger than the right onePython line 22
- swap themPython lines 23 and 24
- the left end of the unsorted part is now in placePython line 27
- 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
, 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
| comparisons | time | |
|---|---|---|
| 1,000 | 499,500 | about 500 microseconds |
| 100,000 | 4,999,950,000 | about 5 seconds |
| 10,000,000 | 49,999,995,000,000 | about 14 hours |
The comparisons are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count 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.
| bestalready in order, the cheapest row | averageshuffled, different numbers in a random order, every order as likely | worstdifferent numbers back to front, one of the dearest rows | |
|---|---|---|---|
| comparisons | between and | ||
| swaps | none | ||
| how the comparisons grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
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 5 | comparisons | swaps |
|---|---|---|
| 1, 2, 3, 4, 5 | 4 | 0 |
| all 120 orders, on average | about 9.14 | 5 |
| 5, 4, 3, 2, 1 | 10 | 10 |
| row of 5 | cocktail shaker sort | bubble sort |
|---|---|---|
| 1, 4, 5, 2, 3 | 10 | 9 |
| all 120 orders, on average | about 9.14 | about 9.26 |
where the formula comes from
Each count in section 3, in small steps. The average comparisons get a floor and a ceiling instead.
the move: count the numbers walk k looks at
the line: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.
the move: open the bracket
the line:why it is allowed: Take away , then give 1 back. For walk 2 of 5 numbers, 5 less 2, plus 1, is 4.
guess it, thenthe move: count the pairs among them
the line:why it is allowed: Neighbouring pairs are one fewer than the numbers. 4 numbers make 3 pairs.
guess it, thenthe move: count the walks
the line:why it is allowed: With for , 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.
guess it, thenthe move: no row costs more
the line: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 , walk comparing pairs. For 5 numbers, at most 4 + 3 + 2 + 1, as drawn.
guess it, thenthe move: see why this row never stops early
the line: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 run.
guess it, thenthe move: add up the walks
the line:why it is allowed: is the comparisons on this row. By lines 6 and 3 all walks run, comparing , then one fewer, down to 1. For 4 numbers, 3 + 2 + 1.
guess it, thenthe move: so this row is one of the dearest
the line: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.
guess it, thenthe move: add them the other way round
the line:why it is allowed: The same numbers in the other order.
guess it, thenthe move: use the page on adding up, its last number here being n - 1
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line:Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15. why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: 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.
guess it, thenthe move: tidy the bracket
the line:why it is allowed: One more than is .
guess it, thenthe move: write the product the other way round
the line:why it is allowed: The same product.
guess it, thenthe move: multiply out the bracket
the line:why it is allowed: lots of , less lots of 1. For 4 numbers, 4 times 3 is 16 less 4.
guess it, thenthe move: halve each part
the line:why it is allowed: Half of a difference is the difference of the halves. For 4 numbers, 12 halved is 8 less 2.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 14 takes , above zero, from . For 4 numbers, 6 is at most 8.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 15, stays under half of .
guess it, thenthe move: a fact for the floor
the line:why it is allowed: Now a floor, for line 20. Half of is at least 1 from 2 numbers on. At 2 numbers, 1 is at most 1.
guess it, thenthe move: multiply both sides by n
the line:why it is allowed: Line 17 times , above zero, so the order holds. For 10 numbers, 10 is at most 50.
guess it, thenthe move: halve both sides
the line:2 1 1 4 2 4 10 5 25 100 50 2,500 Equal at 2 numbers, then the quarter of n squared pulls ahead. why it is allowed: Line 18 halved. For 10 numbers, 5 is at most 25.
guess it, thenthe move: a floor
the line:the first quarter the second, less 2 1 0 1 4 4 2 6 10 25 20 45 100 2,500 2,450 4,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 , at most line 19's , and taking away more leaves less. For 10 numbers, 45 is at least 50 less 25.
guess it, thenthe move: tidy the floor
the line:why it is allowed: Half less a quarter is a quarter.
guess it, thenthe move: read it as a bound
the line: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 is 0, but a floor need only hold for rows long enough.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 22 and 16 bound by the same growth, .
guess it, then
try it with a small : at , line 7 gives , which you can work out by hand
the move: no row costs less
the line:row of 5 walk 1 compares then 1, 2, 3, 4, 5 4 swaps none, stops 3, 2, 5, 1, 4 4 swaps, walks on 5, 4, 3, 2, 1 4 swaps, 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 pairs.
the move: walk once
the line:1, 2, 3, 4, 5, walk by walk. why it is allowed: is the comparisons on a row in order. No pair is wrong, so walk 1 swaps nothing and ends the sort.
guess it, thenthe move: so this row is a cheapest one
the line:why it is allowed: By line 1 no row costs less, and by line 2 this row costs just that.
guess it, thenthe move: a ceiling
the line:why it is allowed: One less than is less than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 4.
guess it, thenthe move: a fact for the floor
the line:why it is allowed: Half of is at least 1 from 2 numbers on.
guess it, thenthe move: a floor
the line:why it is allowed: Line 2 takes away 1, at most line 6's , and taking away more leaves less. For 10 numbers, 9 is at least 10 less 5.
guess it, thenthe move: tidy the floor
the line:why it is allowed: less half of is half of .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8, from 2 numbers on.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 9 and 5 bound by the same growth, .
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: a swap mends one wrong pair
the line: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.
the move: count the swaps as wrong pairs
the line: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.
guess it, thenthe move: average pair by pair
the line:shuffle the numbers 1 and 2 the numbers 1 and 3 the numbers 2 and 3 swaps 1, 2, 3 0 0 0 0 1, 3, 2 0 0 1 1 2, 1, 3 1 0 0 1 2, 3, 1 1 1 0 2 3, 1, 2 0 1 1 2 3, 2, 1 1 1 1 3 in all 3 3 3 9 average 3 over 6 3 over 6 3 over 6 9 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.
guess it, thenthe move: each pair is wrong half the time
the line:the pair 1 and 2 wrong traded, the pair right 2, 1, 3 1, 2, 3 2, 3, 1 1, 3, 2 3, 2, 1 3, 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 .
guess it, thenthe move: count the pairs
the line:why it is allowed: The first number pairs with the after it, the next with one fewer, down to the last two. For 3 numbers, 2 + 1.
guess it, thenthe move: add up the halves
the line:why it is allowed: is the average swaps over every shuffle of different numbers. By lines 3 to 5, a half for each pair. For 3 numbers, three halves.
guess it, thenthe move: put in the first ladder's sum
the line:why it is allowed: By the first ladder's lines 7 to 12, is .
guess it, thenthe move: multiply the fractions
the line:why it is allowed: Half of a half is a quarter. For 3 numbers, 1.5, line 3's 9 over 6.
guess it, thenthe move: multiply out the bracket
the line:why it is allowed: lots of , less lots of 1. For 3 numbers, 9 less 3, over 4, is 1.5.
guess it, thenthe move: take a quarter of each part
the line:why it is allowed: A quarter of a difference is the difference of the quarters.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 10 takes , above zero, from .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 11.
guess it, thenthe move: split off a quarter of n
the line:why it is allowed: Now a floor. Line 8 is a quarter of times ; lines 14 to 19 replace with half of , no bigger, so stays at least that. For 10 numbers, 2.5 times 9 is 22.5.
guess it, thenthe move: a fact for the floor
the line:why it is allowed: Half of is at least 1 from 2 numbers on.
guess it, thenthe move: take both sides away from n
the line:why it is allowed: By line 14, 1 is at most half of , so less 1 is at least less half of . For 10 numbers, 9 is at least 10 less 5.
guess it, thenthe move: tidy the fact
the line:why it is allowed: less half of is half of .
guess it, thenthe move: multiply both sides by a quarter of n
the line:why it is allowed: Line 16 times a quarter of , above zero, so the order holds. For 10 numbers, 22.5 is at least 12.5.
guess it, thenthe move: a floor
the line:why it is allowed: By line 13, is the left side of line 17.
guess it, thenthe move: tidy the floor
the line:why it is allowed: A quarter of times half of is an eighth of times .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 19, from 2 numbers on.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 20 and 12 bound by the same growth, .
guess it, then
try it on small rows: over every order of 3 numbers, the average is
the move: a floor from the swaps
the line:shuffle swaps comparisons 1, 2, 3 0 2 1, 3, 2 1 3 2, 1, 3 1 3 2, 3, 1 2 3 3, 1, 2 2 3 3, 2, 1 3 3 in all 9 17 average 1.5 about 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: is the average comparisons over every shuffle of different numbers, which section 2 estimates by the mean of 20 shuffles. Each swap follows a comparison, so is at least the average swaps, line 8 of the ladder on average swaps.
the move: a simpler floor
the line:why it is allowed: Lines 13 to 19 of the ladder on average swaps show is at least . For 10 numbers, 22.5 is at least 12.5.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 2, from 2 numbers on.
guess it, thenthe move: a ceiling from the dearest rows
the line:why it is allowed: By the first ladder's lines 5 and 7 to 12, no row costs more, so neither does the average.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: By the first ladder's lines 12 to 15, is at most .
guess it, thenthe move: read it as a bound
the line:- line 4,
- line 1,
Line 4's ceiling and line 1's floor. By those lines, lies between them. why it is allowed: By line 5.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 3 and 6 bound by the same growth, . 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.
guess it, then
try it on small rows: over every order of 4 numbers, the average is about 5.58
the move: every pair is wrong
the line: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.
the move: count the pairs
the line:why it is allowed: As line 5 of the ladder on average swaps counts them. For 4 numbers, 3 + 2 + 1.
guess it, thenthe move: count the swaps as wrong pairs
the line:why it is allowed: 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.
guess it, thenthe move: no row makes more
the line:why it is allowed: A row's swaps are its wrong pairs, and no row has more wrong pairs than pairs.
guess it, thenthe move: the first ladder's sum
the line:why it is allowed: By the first ladder's lines 7 to 12. For 4 numbers, 6.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: no pair is wrong
the line:why it is allowed: In a row in order each number is at most every number after it.
the move: count the swaps
the line:why it is allowed: is the swaps on a row in order, its wrong pairs by line 2 of the ladder on average swaps, so none.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: walk 1 swaps only the last pair
the line:2, 4, 6, 8, 10, 1, walk by walk. why it is allowed: Take 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.
the move: walk 2 carries the 1 to the front
the line:after cocktail shaker sort bubble sort the start 2, 4, 6, 8, 10, 1 2, 4, 6, 8, 10, 1 walk 1 2, 4, 6, 8, 1, 10 2, 4, 6, 8, 1, 10 walk 2 1, 2, 4, 6, 8, 10 2, 4, 6, 1, 8, 10 walk 3 1, 2, 4, 6, 8, 10 2, 4, 1, 6, 8, 10 walk 4 stopped 2, 1, 4, 6, 8, 10 walk 5 stopped 1, 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 , over places 1 to , so pairs. Each has the 1 just right of a bigger number, so each swaps, and the row is in order.
guess it, thenthe move: walk 3 swaps nothing
the line:why it is allowed: Places 2 to make 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.
guess it, thenthe move: add up the walks
the line:why it is allowed: is the comparisons on this row, lines 1 to 3 added up. For 6 numbers, 5 + 4 + 3.
guess it, thenthe move: collect the terms
the line:why it is allowed: Three s, 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.
guess it, thenthe move: a ceiling
the line:why it is allowed: Taking 6 from three times leaves less.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 6, from 3 numbers on.
guess it, thenthe move: a fact for the floor
the line:why it is allowed: Twice is at least twice 3 from 3 numbers on. For 6 numbers, 6 is at most 12.
guess it, thenthe move: a floor
the line:why it is allowed: Line 5 takes away 6, at most line 8's twice , and taking away more leaves less. For 6 numbers, 12 is at least 18 less 12.
guess it, thenthe move: tidy the floor
the line:why it is allowed: Three times less twice is .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 10, from 3 numbers on.
guess it, thenthe move: a ceiling and a floor together
the line:why it is allowed: Lines 11 and 7 bound by the same growth, .
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
count it yourself
Follow every step on 4, 3, 2, 1, then check the comparisons against . The swaps are 6 too.
| step | the row | what happens | comparisons | swaps |
|---|---|---|---|---|
| 1 | 4, 3, 2, 1 | There are 4 numbers in a row. Walk right along it comparing each neighbouring pair, then walk back left the same way.4, 3, 2, 1 | 0 | 0 |
| 2 | 4, 3, 2, 1 | 4 is bigger than 3, so they are the wrong way round.4, 3, 2, 1 | 1 | 0 |
| 3 | 3, 4, 2, 1 | Swap them: 3 moves left and 4 moves right.3, 4, 2, 1 | 1 | 1 |
| 4 | 3, 4, 2, 1 | 4 is bigger than 2, so they are the wrong way round.3, 4, 2, 1 | 2 | 1 |
| 5 | 3, 2, 4, 1 | Swap them: 2 moves left and 4 moves right.3, 2, 4, 1 | 2 | 2 |
| 6 | 3, 2, 4, 1 | 4 is bigger than 1, so they are the wrong way round.3, 2, 4, 1 | 3 | 2 |
| 7 | 3, 2, 1, 4 | Swap them: 1 moves left and 4 moves right.3, 2, 1, 4 | 3 | 3 |
| 8 | 3, 2, 1, 4 | 4 is now at the right end of the unsorted part. Nothing bigger is left, so it stays there for good.3, 2, 1, 4 | 3 | 3 |
| 9 | 3, 2, 1, 4 | 2 is bigger than 1, so they are the wrong way round.3, 2, 1, 4 | 4 | 3 |
| 10 | 3, 1, 2, 4 | Swap them: 1 moves left and 2 moves right.3, 1, 2, 4 | 4 | 4 |
| 11 | 3, 1, 2, 4 | 3 is bigger than 1, so they are the wrong way round.3, 1, 2, 4 | 5 | 4 |
| 12 | 1, 3, 2, 4 | Swap them: 1 moves left and 3 moves right.1, 3, 2, 4 | 5 | 5 |
| 13 | 1, 3, 2, 4 | 1 is now at the left end of the unsorted part. Nothing smaller is left, so it stays there for good.1, 3, 2, 4 | 5 | 5 |
| 14 | 1, 3, 2, 4 | 3 is bigger than 2, so they are the wrong way round.1, 3, 2, 4 | 6 | 5 |
| 15 | 1, 2, 3, 4 | Swap them: 2 moves left and 3 moves right.1, 2, 3, 4 | 6 | 6 |
| 16 | 1, 2, 3, 4 | 3 is now at the right end of the unsorted part. Nothing bigger is left, so it stays there for good.1, 2, 3, 4 | 6 | 6 |
| 17 | 1, 2, 3, 4 | Only 2 is left, so it is in place too.1, 2, 3, 4 | 6 | 6 |
| 18 | 1, 2, 3, 4 | In order, after 6 comparisons and 6 swaps.1, 2, 3, 4 | 6 | 6 |
In all, 6 comparisons. The formula from section 4, , gives at : 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, 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.
- bubble sort
- cocktail shaker sort
- insertion sort
- selection sort
- shell sort
- quick sort
- randomised quick sort
- merge sort
- heap sort
| way | best | average | worst | extra memory | keeps equal items in order | works in place | reach for it when |
|---|---|---|---|---|---|---|---|
| bubble sort | a few spare places (the walk number, the pair's place, whether the walk swapped, room for a number while two swap), the same however long the row | yes | yes | you are learning how sorting works; for real work, insertion sort, which on every order of up to 8 different numbers makes no more comparisons, counted order by order | |||
| cocktail shaker sort | a few spare places, the same however long the row | yes | yes | you are learning how sorting works; for real work, insertion sort | |||
| insertion sort | room for a few numbers (the number being placed, where its slide has reached, which number is next), the same however long the row | yes | yes | the row is short, a few dozen numbers, or nearly in order | |||
| selection sort | room for a few numbers (the place being filled, where the smallest so far stands, the number looked at, one held during a swap), the same however long the row | no | yes | moving a number costs far more than comparing two, and the row is short | |||
| shell sort | not known; between and | not worked out here; between and | a few spare places (the gap, the number picked up, its place), the same however long the row | no | yes | you want a few lines of code and no room beyond the row. On this site's shuffles of 200 to 10,000 numbers it averaged under a fifth of insertion sort's comparisons | |
| quick sort | a list of the parts still to sort, two memory places each. That is two places for each number on a row in order, and far fewer on a shuffle, about 51 for 100,000 numbers. So this plain version does not work in place, as its spare room grows with the row | no | no | you want a fast sort on shuffled rows with no second row, and equal items need not keep their order; use a version with a random or middle pivot | |||
| randomised quick sort | at most , as every row of different numbers averages that over the picks; a row with equal numbers can cost a little less | , a row of equal numbers, whatever the picks; no run costs more, since a pair meets at most once | a list of the parts waiting to be sorted, each kept as its first and last place. On average far shorter than the row, about 66 places for a million numbers. Unlucky picks can make it grow with the row | no | no | you want quick sort without a dear row in order, and equal items need not keep their order | |
| merge sort | a second row as long as the row | yes | no | you need comparisons growing no faster than on every row, equal items kept in order, or a file too big for memory sorted | |||
| heap sort | , every number the same | , shuffled; measured, no formula worked out here | , the dearest row; this page finds it only for short rows, by trying every order | a few places, however long the row | no | yes | you need a sort with no slow row and no second row, and equal items need not keep their order |
| counting sort | steps, every row alike | steps | steps, every row alike | a second row of n places and 10 tallies | yes | no | the numbers are small whole numbers, such as ratings from 0 to 9, and equal ones must keep their order |
| radix sort | placings, every number below 10 | placings, between the best and the worst, as every order costs the same | placings, three passes for numbers up to 999 | a second row of n places and 10 tallies | yes | no | many whole numbers with few digits, such as numbers from 0 to 999 |
- extra memory:
- the room it needs on top of the input itself, while it runs.
- keeps equal items in order:
- people sorted by age keep the order they arrived in within each age; in general, two items equal in what is being sorted come out in the order they went in.
- works in place:
- it rearranges the input where it stands, with only a few spare places, rather than building a copy; a different sense from a number being in place, in its final position.