Cocktail shaker sort is bidirectional Bubble Sort. A forward pass swaps adjacent inversions and fixes the largest remaining value at the right boundary. A backward pass then fixes the smallest remaining value at the left boundary. Both boundaries shrink after a round.

The backward pass repairs Bubble Sort’s asymmetry: a small value near the tail can travel many positions toward the front in one round instead of one position per forward pass. Strict comparison keeps equal values from crossing, so the result is stable. Its value is explanatory rather than production performance.

Visualization

The forward sweep carries the largest live value to the right edge. The backward sweep carries the smallest live value to the left edge. A complete sweep with no swap proves that no adjacent inversion remains, so the array is sorted.

Complexity
n
number of elements in the array

Boundary and implementation

Early exit depends on stopping after a swap-free round. Removing that flag schedules every shrinking pass even when the input is already ordered. Bidirectional motion improves some displaced-value patterns, but Insertion Sort is usually the better simple algorithm for small or nearly sorted inputs.

Questions

References