Cocktail shaker sort runs Bubble Sort in both directions. The forward pass fixes the largest remaining value at the right boundary. The backward pass fixes the smallest at the left. Both boundaries then move inward.

The backward pass addresses Bubble Sort’s main weakness. A small value near the tail can move several positions toward the front in one round instead of one position per forward pass. Strict comparison keeps equal values from crossing, so the sort remains stable. It is still mainly useful for explaining adjacent-swap behavior.

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

Early exit and stability

Early exit requires the swap flag. Without it, every shrinking pass runs even when the input is already ordered. Two-way movement helps with some displaced values, but Insertion Sort is usually the better simple choice for small or nearly sorted inputs.

References