Typorithm · medium

Cocktail Shaker Sort

▷ Interactive algorithm labcocktail-shaker-sortsortingbubble-sortbidirectionalquadratic-time
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Cocktail Shaker Sort

0%

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.

Preparing algorithm lab…
01

Scan forward, then backward.

02

Shrink both boundaries.

03

Use swapped for early exit.

04

Adjacent swaps make it stable.

05

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Left boundary

start marks the left edge that still needs checking.

let start = 0

2. Right boundary

end marks the right edge that still needs checking.

let end = arr.length - 1

3. Swap flag

The flag keeps passes going only while swaps happen.

let swapped = true

4. Forward pass

Move large values right, like Bubble Sort.

for (let i = start; i < end; i++)

5. Swap neighbors

Swap adjacent values that are out of ascending order.

[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]

6. Early exit

If the forward pass made no swaps, the array is sorted.

if (!swapped) break

7. Shrink right

The largest unsorted value is now fixed at the right edge.

end--

8. Backward pass

Move small values left by scanning backward.

for (let i = end - 1; i >= start; i--)

9. Grow left

The smallest unsorted value is now fixed at the left edge.

start++

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Cocktail Shaker Sort: Visual Walkthrough & Practice · Typorithm | ApplyDjinn