1. Left boundary
start marks the left edge that still needs checking.
let start = 0Typorithm · medium
Step 1 of 8 · intro card
Sorting Algorithms
Cocktail Shaker Sort is a bidirectional Bubble Sort: one pass moves large values right, the next moves small values left.
The algorithm keeps both a left boundary and a right boundary.
A forward pass compares neighbors and pushes a large value toward the right side.
A backward pass compares neighbors in reverse and pulls a small value toward the left side.
If a full pass has no swaps, the algorithm exits early.
It is still O(n^2), but it can handle values misplaced in both directions more visibly than Bubble Sort.
Scan forward, then backward.
Shrink both boundaries.
Use swapped for early exit.
Adjacent swaps make it stable.
Worst-case time remains O(n^2).
function cocktailShakerSort(arr) {
let start = 0;
let end = arr.length - 1;
let 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;
}
}
if (!swapped) break;
swapped = false;
end--;
for (let i = end - 1; i >= start; i--) {
if (arr[i] > arr[i + 1]) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true;
}
}
start++;
}
return arr;
}Connect each part of the code to the concept before you type.
start marks the left edge that still needs checking.
let start = 0end marks the right edge that still needs checking.
let end = arr.length - 1The flag keeps passes going only while swaps happen.
let swapped = trueMove large values right, like Bubble Sort.
for (let i = start; i < end; i++)Swap adjacent values that are out of ascending order.
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]If the forward pass made no swaps, the array is sorted.
if (!swapped) breakThe largest unsorted value is now fixed at the right edge.
end--Move small values left by scanning backward.
for (let i = end - 1; i >= start; i--)The smallest unsorted value is now fixed at the left edge.
start++Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input[5,1,4,2,8]
One temporary value and a fixed number of indices. In-place does not mean zero extra memory. The input array is not counted as extra space.
One reusable value slot. Empty until the next operation needs it.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state