AlgoLab

O(n²)·O(1) space·stable
645559896316373459948511843281951114277

Starting cocktail shaker sort on an array of 20 items.

Starting cocktail shaker sort on an array of 20 items.
  1. 1set the low and high boundaries to the first and last index
  2. 2sweep forward from the low boundary to the high boundary
  3. 3compare each adjacent pair while sweeping forward
  4. 4if the left value is greater than the right value, swap them
  5. 5move the high boundary in by one; if that forward sweep made no swaps, the array is sorted
  6. 6sweep backward from the high boundary to the low boundary
  7. 7compare each adjacent pair while sweeping backward
  8. 8if the left value is greater than the right value, swap them
  9. 9move the low boundary in by one; if that backward sweep made no swaps, the array is sorted
  10. 10the array is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(n)
AverageO(n²)
WorstO(n²)
Extra spaceO(1)
StableYes
n² at n=20 predicts 400; this run took 0.

Cocktail shaker sort

Cocktail shaker sort is bubble sort with a second sweep added: after a forward pass carries the largest remaining value to the end, a backward pass immediately carries the smallest remaining value to the front, before the boundaries close in from both ends and the two passes repeat.

When it is the right choice

It is a genuine improvement on bubble sort only for a specific input shape: a few small values sitting near the end of an otherwise sorted array, where plain bubble sort needs one pass per position to walk each of them to the front while a single backward sweep here carries them all in one pass. On most other inputs the extra bookkeeping per pass makes it no faster than bubble sort in practice, and both remain far slower than insertion sort or any O(n log n) sort.

How it works

Worth noticing

Cost

Best
O(n)
Average
O(n²)
Worst
O(n²)
Extra space
O(1)
Stable
Yes

Worth comparing

All algorithms