built byKyle

Cocktail Sort

Bubble sort that shakes in both directions, like a bartender mixing a cocktail.

0 elements
>Ready — Cocktail Sort
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Analysis
BEST O(n)
AVG O(n²)
WORST O(n²)
SPACE O(1)
STABLE

Cocktail Shaker Sort (a.k.a. Bidirectional Bubble Sort) is a variation of Bubble Sort that traverses the array in both directions alternately. The forward pass bubbles the largest element to the end, then the backward pass bubbles the smallest to the beginning. It’s slightly better than Bubble Sort for arrays where small elements are stuck at the end ("turtles"), but still O(n²).

Edit in playground