Cocktail Shaker Sort

A bidirectional variation of bubble sort that alternates between forward and backward passes through the list, moving the largest unsorted element right and the smallest unsorted element left in each full iteration.

Algorithm Information

Time Complexity

Best: O(n)
Average: O(n²)
Worst: O(n²)

Space Complexity

O(1)

Properties

Stable sorting algorithm
In-place sorting
Bidirectional bubble sort
Handles turtles better than bubble sort
1/49
Speed: 1x

Algorithm Code

1function cocktailShakerSort(arr) {
2 const n = arr.length;
3 let start = 0;
4 let end = n - 1;
5 let swapped = true;
6
7 while (swapped) {
8 swapped = false;
9
10 // Forward pass: left to right
11 for (let i = start; i < end; i++) {
12 if (arr[i] > arr[i + 1]) {
13 [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
14 swapped = true;
15 }
16 }
17
18 if (!swapped) break;
19 end--;
20
21 swapped = false;
22
23 // Backward pass: right to left
24 for (let i = end - 1; i >= start; i--) {
25 if (arr[i] > arr[i + 1]) {
26 [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
27 swapped = true;
28 }
29 }
30
31 start++;
32 }
33
34 return arr;
35}

Variable State

start:0
end:6
swapped:true
n:7

Call Stack

cocktailShakerSort

Array Visualization

Watch how Cocktail Shaker Sort processes the array step by step

64
0
34
1
25
2
12
3
22
4
11
5
90
6

Statistics

Comparisons0
Swaps0
Step1 / 49

Legend

Comparing
Active / Swapping
Sorted
Unsorted

Starting cocktail shaker sort algorithm

How Cocktail Shaker Sort Works

Learn the fundamentals of cocktail shaker sort through step-by-step explanations, code examples, and key concepts.