Cocktail Shaker Sort
Bidirectional bubble sort that passes through the list in both directions each iteration, moving large items to the end and small items to the beginning.
Visualization
Interactive visualization for Cocktail Shaker Sort
Cocktail Shaker Sort Visualization
Interactive visualization with step-by-step execution
Implementation
1function cocktailShakerSort(arr: number[]): number[] {
2 const a = [...arr];
3 let start = 0, end = a.length - 1;
4 let swapped = true;
5 while (swapped) {
6 swapped = false;
7 for (let i = start; i < end; i++) {
8 if (a[i] > a[i + 1]) { [a[i], a[i + 1]] = [a[i + 1], a[i]]; swapped = true; }
9 }
10 if (!swapped) break;
11 swapped = false;
12 end--;
13 for (let i = end; i > start; i--) {
14 if (a[i - 1] > a[i]) { [a[i - 1], a[i]] = [a[i], a[i - 1]]; swapped = true; }
15 }
16 start++;
17 }
18 return a;
19}Deep Dive
Theoretical Foundation
Runs alternating forward and backward passes that bubble extremes toward their ends. This can reduce passes on partially sorted arrays compared to plain bubble sort.
Complexity
Time
O(n)
O(n²)
O(n²)
Space
O(1)
Applications
Industry Use
Educational demos
Tiny or nearly sorted arrays
Use Cases
Related Algorithms
Quicksort
A highly efficient, in-place sorting algorithm that uses divide-and-conquer strategy. Invented by Tony Hoare in 1959, it remains one of the most widely used sorting algorithms due to its excellent average-case performance and cache efficiency.
Merge Sort
A stable, divide-and-conquer sorting algorithm with guaranteed O(n log n) performance.
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. This process is repeated until the entire array is sorted. Named for the way larger elements 'bubble' to the top (end) of the array.
Insertion Sort
Insertion Sort is a simple, intuitive sorting algorithm that builds the final sorted array one element at a time. It works similarly to how people sort playing cards in their hands - picking each card and inserting it into its correct position among the already sorted cards. Despite its O(n²) time complexity, Insertion Sort is efficient for small datasets and nearly sorted arrays, making it practical for real-world applications.