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, stats) {
  const n = arr.length;
  let start = 0, end = n - 1, swapped = true;
  while (swapped) {
    swapped = false;
    for (let i = start; i < end; i++) {
      compare(i, i + 1);
      if (arr[i] > arr[i + 1]) {
        [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
        swap(i, i + 1);
        swapped = true;
      }
    }
    end--;
    if (!swapped) break;
    swapped = false;
    for (let i = end; i > start; i--) {
      compare(i, i - 1);
      if (arr[i] < arr[i - 1]) {
        [arr[i], arr[i - 1]] = [arr[i - 1], arr[i]];
        swap(i, i - 1);
        swapped = true;
      }
    }
    start++;
    checkpoint(start, Math.ceil(n / 2));
  }
  for (let i = 0; i < n; i++) markSorted(i);
}