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
- Sweep forward, swapping adjacent out-of-order pairs; the largest value reaches the end.
- Shrink the window from the right.
- Sweep backward, swapping out-of-order pairs; the smallest value reaches the front.
- 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?