sort.cny.shStart a race
Back to library
04 / 18Algorithm

Cocktail Shaker Sort

Bubble sort, but sloshing both directions each pass.

StableIn-place
BestO(n)
AverageO(n²)
WorstO(n²)
01How it works

Bubble sort that reverses direction each pass — left-to-right to bubble the maximum up, then right-to-left to sink the minimum down. Small "turtle" values trapped near the back move toward the front twice as fast as in plain bubble sort.

02Best for

Mostly-sorted data with a handful of out-of-place elements near either end. The bidirectional sweep catches both sides in a single round-trip, so one full cycle often finishes the job.

03Avoid when

Any workload a real library sort could handle. Still O(n²) on average — cocktail only trims the constant, not the order of growth.