Algorithms · Visualized
Cocktail Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Cocktail Sort (also called Shaker Sort) is a two-directional Bubble Sort. Time: O(n²) average, O(n²) worst; space: O(1) — sorts in place.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Cocktail Sort
SortingCocktail Sort (also called Shaker Sort) is a two-directional Bubble Sort. Instead of only sweeping left-to-right, it alternates: one pass bubbles the largest value to the right, the next pass bubbles the smallest value to the left, shrinking the unsorted range from both ends each round.
How Cocktail Sort Works
- Do a forward pass from left to right, swapping adjacent out-of-order elements — this pushes the largest value to the end.
- Shrink the right boundary since the last element is now sorted.
- Do a backward pass from right to left, swapping adjacent out-of-order elements — this pushes the smallest value to the start.
- Shrink the left boundary since the first element is now sorted.
- Repeat forward and backward passes, shrinking both ends, until a pass completes with no swaps.
Cocktail Sort Worked Example
Input: [5, 1, 4, 2, 8, 0]
Forward pass pushes 8 to the end: [1,4,2,5,0,8]. Backward pass pushes 0 to the front: [0,1,4,2,5,8]. Forward pass again on the middle section: [0,1,2,4,5,8]. No more swaps needed on the next pass — sorted.
def cocktail_sort(a):
n = len(a)
start, end = 0, n - 1
while start < end:
for i in range(start, end):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
end -= 1
for i in range(end, start, -1):
if a[i] < a[i - 1]:
a[i], a[i - 1] = a[i - 1], a[i]
start += 1
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Cocktail Sort Time & Space Complexity
When to Use Cocktail Sort
- Slightly faster than plain Bubble Sort in practice when small values are stuck near the end of the array (a 'turtle' problem Bubble Sort handles poorly).
- Teaching bidirectional passes as a simple optimisation idea.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.