FlowLab Logo

Cocktail Shaker Sort Visualizer

SlowFast
64
[0]
34
[1]
25
[2]
12
[3]
22
[4]
11
[5]
90
[6]
Forward Pass
Backward Pass
Swapping
Sorted
Operation Logs
No operations yet
Algorithm Info
Time Complexity: O(n²) worst and average case, O(n) best case
Space Complexity: O(1) - in-place sorting
Stable: Yes - maintains relative order of equal elements
How it works: Bidirectional bubble sort. Bubbles largest elements right, then smallest elements left in alternating passes.
Advantage: Slightly better than bubble sort - can move elements in both directions
Also known as: Bidirectional Bubble Sort or Shaker Sort
Implementation
function cocktailShakerSort(arr) {
  const n = arr.length;
  let left = 0;
  let right = n - 1;
  let swapped = true;
  
  while (swapped && left < right) {
    swapped = false;
    
    // Forward pass (left to right)
    for (let i = left; i < right; i++) {
      if (arr[i] > arr[i + 1]) {
        [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
        swapped = true;
      }
    }
    right--; // Last element is now in place
    
    if (!swapped) break; // Array is sorted
    
    // Backward pass (right to left)
    for (let i = right; i > left; i--) {
      if (arr[i - 1] > arr[i]) {
        [arr[i - 1], arr[i]] = [arr[i], arr[i - 1]];
        swapped = true;
      }
    }
    left++; // First element is now in place
  }
  
  return arr;
}