COMPARISON SORTS
Cocktail Sort, visualised
Cocktail sort (cocktail shaker sort) runs bubble-sort passes alternately left-to-right and right-to-left, carrying large values to the right end and small values to the left end.
Run Cocktail Sort in the visualizer →
Opens the Sorting Cinema visualizer with 16 elements in English.
How it works
- Compare and swap neighbours from left to right; the maximum is fixed at the right end.
- If no swap happened, stop.
- Then compare and swap neighbours from right to left; the minimum is fixed at the left end.
- Narrow both ends and keep going back and forth until no swaps occur.
Complexity and stability
- Best
- O(n)
- Average
- O(n²)
- Worst
- O(n²)
- Extra space
- O(1)
- Stability
- Stable
This app's implementation stops after a pass with no swaps, so sorted input takes one forward pass, O(n). In general it relies on neighbour swaps, giving O(n²).
Source of facts: Complexity is derived from the steps of this app's implementation (src/SortingCinema.jsx).
Trace on a small array
The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.
| # | Operation | Array after |
|---|---|---|
| 1 | Compare [0]=5 and [1]=2 | [5, 2, 4, 1, 3] |
| 2 | Swap [0]=5 and [1]=2 | [2, 5, 4, 1, 3] |
| 3 | Compare [1]=5 and [2]=4 | [2, 5, 4, 1, 3] |
| 4 | Swap [1]=5 and [2]=4 | [2, 4, 5, 1, 3] |
| 5 | Compare [2]=5 and [3]=1 | [2, 4, 5, 1, 3] |
| 6 | Swap [2]=5 and [3]=1 | [2, 4, 1, 5, 3] |
| 7 | Compare [3]=5 and [4]=3 | [2, 4, 1, 5, 3] |
| 8 | Swap [3]=5 and [4]=3 | [2, 4, 1, 3, 5] |
…and so on. In this trace, 17 compare / swap / write operations in total produce [1, 2, 3, 4, 5].
Suitable inputs and caveats
- Compare with bubble sort: a small value near the right end is carried left in a single backward pass.
- Sorted input finishes after the first forward pass (unlike this app's bubble sort).
- It swaps neighbours only when strictly out of order, so it is stable.
FAQ
How is cocktail sort different from bubble sort?
Bubble sort passes in one direction only; cocktail sort goes back and forth. In this app, cocktail sort also stops after a swap-free pass while bubble sort does not.
Is cocktail sort stable?
Yes. It swaps neighbours only when they are strictly out of order, so equal values keep their order.