function cocktailSort(array: number[]) {let low = 0, high = array.length - 1;
while (low < high) { for (let j = low; j < high; j++) {if (array[j] > array[j + 1]) swap(array, j, j + 1);
}
high--;
for (let j = high; j > low; j--) {if (array[j - 1] > array[j]) swap(array, j - 1, j);
}
low++;
}
}
Start: 24 values. Each round sweeps right to carry the largest up, then left to carry the smallest down.
Understanding Cocktail shaker
The idea
Cocktail shaker sort is bubble sort that changes direction after every pass: a sweep to the right carries the largest unsorted value to its final place, then a sweep to the left carries the smallest one to its place. The unsorted window shrinks from both ends.
The point is the turtle: in plain bubble sort a small value near the end moves left only one position per pass, so it can cost as many passes as there are elements. Sweeping back picks it up in one go. The worst case stays quadratic, but on typical input it roughly halves the number of passes.
The four stages
Complexity
Versus its siblings
Pseudocode
COCKTAILSORT(array)
low ← 0; high ← n − 1
while low < high
sweep j from low to high − 1: swap array[j], array[j + 1] if out of order; high ← high − 1
sweep j from high down to low + 1: swap array[j − 1], array[j] if out of order; low ← low + 1
When to use
Pitfalls
History
Also called bidirectional bubble sort, shaker sort or ripple sort, it appears in Knuth's 1973 volume on sorting as a cure for the turtle problem, with the remark that it still does not beat straight insertion. The cocktail name comes from the back-and-forth motion of shaking a drink.