Cocktail Shaker Sort, explained step by step

Cocktail Shaker Sort is a bidirectional Bubble Sort. Each round sweeps left-to-right to push the largest value to the end, then right-to-left to pull the smallest value to the front, shrinking the unsorted window from both sides.

Intuition: Shake a cocktail back and forth — heavy items sink one way, light items float the other.

How it works

  1. Sweep forward, swapping adjacent out-of-order pairs; the largest value reaches the end.
  2. Shrink the window from the right.
  3. Sweep backward, swapping out-of-order pairs; the smallest value reaches the front.
  4. Shrink the window from the left and repeat until a full round makes no swaps.

Complexity

  • Best: O(n)
  • Average: O(n²)
  • Worst: O(n²)
  • Space: O(1)
  • Stable: yes

When to use it

Teaching, or small arrays where small values sit near the end (where plain Bubble Sort is slow).

Interview questions

  • What is the "turtle" problem in Bubble Sort and how does Cocktail Sort address it?
  • Is Cocktail Sort asymptotically faster than Bubble Sort?

Compare Cocktail Shaker Sort

Open Cocktail Shaker Sort in the visualiser