Algorithm Visualiser by Tsvetozar Biserov

Cocktail Shaker Sort

  • Ω( n )
  • Θ( n2 )
  • O( n2 )
  • space O( 1 )

Cocktail shaker sort is bubble sort that changes direction. A rightward sweep pushes the largest value of the unsorted window to its right edge, then a leftward sweep pulls the smallest value to the left edge, and the window closes in from both sides. It still swaps only adjacent neighbours, so it makes the same number of swaps as bubble sort and keeps equal keys in their original order.

Array
Comparator strip Index down, time to the right
100 elements
×20 steps/frame

Comparisons 1
—
Reads 2
—
Writes 2
—
Swaps 3
—
Real time 4
—
Visual time 4
—
  1. Comparisons count only element-against-element checks; loop and index checks are never counted.
  2. Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
  3. A swap counts once, as a swap. It is never also counted as a read or a write.
  4. Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.

How cocktail shaker sort works

On [5, 2, 6, 1, 4, 3] the first rightward sweep is identical to bubble sort. It produces [2, 5, 6, 1, 4, 3], then [2, 5, 1, 6, 4, 3], [2, 5, 1, 4, 6, 3] and [2, 5, 1, 4, 3, 6]. The 6 is home, so the window shrinks to indexes 0 to 4 and the direction flips.

The leftward sweep begins at the pair of cells just inside the finished edge. It swaps 3 and 4 to give [2, 5, 1, 3, 4, 6], finds 1 and 3 in order, then swaps 5 with 1 and finally 2 with 1, leaving [2, 1, 5, 3, 4, 6] and then [1, 2, 5, 3, 4, 6]. The 1 sat in the middle of the array and moved two places in one sweep. Plain bubble sort would have moved it a single place per sweep.

The window is now indexes 1 to 4. A second rightward sweep swaps 5 and 3 to get [1, 2, 3, 5, 4, 6], and swaps 5 and 4 to reach [1, 2, 3, 4, 5, 6]. One short leftward sweep over two pairs finds nothing and ends the run. The total is 14 comparisons and 9 swaps, the same figures bubble sort gets on this input, because every adjacent swap removes one inversion and the array has nine of them.

Cocktail Shaker Sort on 5 2 6 1 4 3, one swap or write at a time. Indexes count from 0.
Step Change Array after
1 Swap indexes 0 and 1 2 5 6 1 4 3
2 Swap indexes 2 and 3 2 5 1 6 4 3
3 Swap indexes 3 and 4 2 5 1 4 6 3
4 Swap indexes 4 and 5 2 5 1 4 3 6
5 Swap indexes 3 and 4 2 5 1 3 4 6
6 Swap indexes 1 and 2 2 1 5 3 4 6
7 Swap indexes 0 and 1 1 2 5 3 4 6
8 Swap indexes 2 and 3 1 2 3 5 4 6
9 Swap indexes 3 and 4 1 2 3 4 5 6

All 9 changes are shown.

Pseudocode

lo = 0, hi = n - 1
while lo < hi
  swapped = false
  for i = lo to hi - 1
    if a[i + 1] < a[i]
      swap a[i], a[i + 1]
      swapped = true
  hi = hi - 1
  for i = hi down to lo + 1
    if a[i] < a[i - 1]
      swap a[i], a[i - 1]
      swapped = true
  lo = lo + 1
  if not swapped
    stop

Why these complexities

Sorted input is the best case. The first rightward sweep makes n-1 comparisons and sees no swap, and the loop stops before ever turning around, so the cost is n-1 comparisons and no swaps. If the right-hand sweep does swap, the left-hand sweep still runs, and the run ends after the first sweep, in either direction, that swaps nothing.

The average and worst cases remain O(n²), and the reason is stronger than a loose analysis. Each swap of two neighbours removes exactly one inversion, and a random permutation holds about n(n-1)/4 of them, so any algorithm that only exchanges adjacent items must do that many swaps. Alternating directions trims the number of comparisons by a constant factor on some inputs, but it cannot touch the swap count. A reversed array is the worst case: every pair is an inversion and the work matches bubble sort.

Where the second direction pays is the turtle case. Take a sorted array whose smallest value sits in the last cell. Bubble sort needs about n sweeps and roughly n²/2 comparisons to carry it to the front, while the leftward sweep of cocktail sort does it in one go, and the run finishes after about three sweeps of roughly n comparisons each. Space is constant: a start marker, an end marker and a flag.

Measured on this site

Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.

Input Comparisons Writes Swaps
Random 460 0 311
Already sorted 31 0 0
Reversed 496 0 496
Few distinct values 391 0 169

When to use it

Use it as a classroom step up from bubble sort, to show how a small change fixes the turtle problem. In practice insertion sort or a library sort is a better choice.

Frequently asked questions

How is cocktail shaker sort different from bubble sort?

It alternates direction. A forward pass carries the largest element to the end, then a backward pass carries the smallest to the start, so small elements near the end no longer crawl.

Is it faster than bubble sort?

Only by a constant factor on some inputs. The worst and average cases are still O(n²).

Is cocktail shaker sort stable?

Yes. Like bubble sort it only swaps neighbours that are strictly out of order.

Why does the end marker move before the leftward sweep?

The rightward sweep has just placed the largest value of the window at its right edge, so that cell is final. Decreasing the end marker first means the leftward sweep starts one cell inside and never compares against the finished cell. In the trace the backward sweep therefore begins with the pair at indexes 3 and 4, not 4 and 5.

What input makes cocktail sort clearly better than bubble sort?

Data that is nearly sorted but has a few small values at the far right. Large values at the far left are no problem for either, since a rightward sweep carries them all the way. Bubble sort moves a stray small value left by one cell per sweep, and cocktail sort moves it all the way in one leftward sweep. For an otherwise sorted array with one small value at the end, the difference is about n²/2 comparisons against roughly 3n.

Background

There is no known inventor. The idea of alternating the direction of bubble sort has been rediscovered many times, which is why it travels under so many names: shaker sort, ripple sort, shuttle sort, bidirectional bubble sort. The cocktail name comes from the back-and-forth motion of a bartender's shaker.

Knuth treats bubble sort and its refinements in his section on sorting by exchanging and uses inversion counts to show why such refinements cannot escape quadratic time. The method survives as a teaching example for the turtle problem and as a reminder that a cleverer scan order does not change the lower bound for adjacent swaps.

References

  • Knuth, The Art of Computer Programming, vol. 3, section 5.2.2 (Sorting by Exchanging)
  • Knuth, The Art of Computer Programming, vol. 3, section 5.1.1 (Inversions)
  • Sedgewick, Algorithms in C, Parts 1-4, chapter 6 (Elementary Sorting Methods)

Compare with

Algorithm Average time Worst time
Bubble Sort Θ( n2 ) O( n2 )
Comb Sort Θ( n2 ) O( n2 )
Gnome Sort Θ( n2 ) O( n2 )
Odd-Even Sort Θ( n2 ) O( n2 )
Quick Sort Θ( n log n ) O( n2 )
3-Way Quick Sort Θ( n log n ) O( n2 )
Dual-Pivot Quick Sort Θ( n log n ) O( n2 )
Big O notation
Best time Ω( n ) good
Average time Θ( n2 ) poor
Worst time O( n2 ) poor
Worst space O( 1 ) good

Properties

Stable
Yes
In place
Yes
Adaptive
Yes
Comparison-based
Yes