Back to Home

Cocktail Shaker Sort

A bidirectional variation of bubble sort that traverses the list in both directions alternately, improving performance on certain types of data.

Visualization

Step 1 / 17
Speed:

Details

Analogy

Imagine a cocktail shaker moving back and forth. Just as a bartender shakes a cocktail up and down to mix ingredients, this algorithm 'shakes' the array by sorting from left to right, then right to left, repeatedly. This bidirectional approach settles both large and small elements faster than one-directional bubble sort.

Purpose

To sort an array more efficiently than standard bubble sort by alternating between forward and backward passes. Each forward pass moves the largest unsorted element to its final position, while each backward pass moves the smallest unsorted element to the beginning.

Use Cases

More efficient than bubble sort for lists with elements that need to move long distances, especially when small elements are at the end (the 'rabbit and turtle' problem). Useful for educational purposes to demonstrate algorithm optimization. Sometimes used in embedded systems where simplicity is important but better performance than bubble sort is needed.

Algorithm Steps

Line 1
1
function cocktailShakerSort(array):
2
start = 0
3
end = length(array) - 1
4
swapped = true
5
while swapped:
6
swapped = false
7
for i = start to end - 1:
8
if array[i] > array[i + 1]:
9
swap(array[i], array[i + 1])
10
swapped = true
11
if not swapped: break
12
end = end - 1
13
swapped = false
14
for i = end - 1 down to start:
15
if array[i] > array[i + 1]:
16
swap(array[i], array[i + 1])
17
swapped = true
18
start = start + 1
19
return array
Current
Executed
Pending

Explanation

What's Happening?

Step 1/17

Initial array: [5, 1, 4, 2, 8, 0, 2]. We'll sort by alternating forward and backward passes.

Updates with each step • Clickfor full view

Code Implementation

def cocktail_shaker_sort(arr):
    n = len(arr)
    start = 0
    end = n - 1
    swapped = True

    while swapped:
        swapped = False

        # Forward pass
        for i in range(start, end):
            if arr[i] > arr[i + 1]:
                arr[i], arr[i + 1] = arr[i + 1], arr[i]
                swapped = True

        if not swapped:
            break

        end -= 1
        swapped = False

        # Backward pass
        for i in range(end - 1, start - 1, -1):
            if arr[i] > arr[i + 1]:
                arr[i], arr[i + 1] = arr[i + 1], arr[i]
                swapped = True

        start += 1

    return arr
Cocktail Shaker Sort - Interactive Visualization | AlgoViz | AlgoViz