Cocktail Shaker Sort visualization

Bubble sort that alternates direction, moving large values right and small values left.

A forward pass pushes the maximum to the right edge; a backward pass pulls the minimum to the left edge. The unsorted window shrinks from both sides.

It fixes bubble sort's "turtle" problem, where small values near the end move left only one step per pass.

Complexity

Time: best O(n), average O(n²), worst O(n²). Space: O(1). Difficulty: Beginner.

Pseudocode

procedure cocktailSort(A):
  lo ← 0; hi ← n−1; swapped ← true
  while swapped:
    swapped ← false
    for j ← lo to hi−1:  if A[j] > A[j+1]: swap, swapped ← true
    hi ← hi − 1
    for j ← hi down to lo+1:  if A[j−1] > A[j]: swap, swapped ← true
    lo ← lo + 1

More sorting algorithms