tap for sound

Cocktail Shaker Sort Visualization

Cocktail Shaker Sort is Bubble Sort that runs forwards and then backwards, so small values move quickly too.

How it works

Cocktail Shaker Sort fixes one weakness of Bubble Sort. A forward pass carries the largest value to the end; a backward pass then carries the smallest value to the front. Alternating directions means values that are far from home in either direction move quickly.

It is still O(n²) on random data, but it usually needs fewer passes than Bubble Sort, especially when a few small values start near the end. Like Bubble Sort it is stable and works in place.

What to watch for

Watch the sorted region grow from both ends at once as the passes sweep back and forth.

Complexity

Best
n
Average
n²
Worst
n²
Extra space
1
Stable
Yes

Race it

Same shuffle, same speed, one winner: Cocktail Shaker vs Bubble. Or open the studio to try other layouts, sizes and speeds, and make a video of it.

FAQ

Is Cocktail Shaker Sort faster than Bubble Sort?

Usually a little, by fewer passes, but both are O(n²).

Is it stable?

Yes, it only swaps neighbours that are out of order.