Cocktail Shaker Sort

A variant of bubble sort that traverses the list in both directions alternately. Helps avoid the "turtle" problem (small values at the end).

Best O(n) Avg O(n²) Worst O(n²) Space O(1) Stable Yes In-place Yes Comparison-based

How it works

A variant of bubble sort that traverses the list in both directions alternately. Helps avoid the "turtle" problem (small values at the end).

Implementation

function cocktailSort(arr) {
  let start = 0, end = arr.length - 1, swapped = true;
  while (swapped) {
    swapped = false;
    for (let i = start; i < end; i++) {
      if (arr[i] > arr[i+1]) {
        [arr[i], arr[i+1]] = [arr[i+1], arr[i]];
        swapped = true;
      }
    }
    end--;
    for (let i = end; i > start; i--) {
      if (arr[i] < arr[i-1]) {
        [arr[i], arr[i-1]] = [arr[i-1], arr[i]];
        swapped = true;
      }
    }
    start++;
  }
}