Insertion Sort vs Cocktail Shaker Sort
Across our 3 test inputs, Insertion Sort needed 85 comparisons in total versus 101 for Cocktail Shaker Sort.
Head-to-head on identical inputs (comparisons)
| Input | Insertion Sort | Cocktail Shaker Sort |
|---|---|---|
| Random order | 30 | 39 |
| Nearly sorted | 10 | 17 |
| Reversed | 45 | 45 |
Complexity
| Insertion Sort | Cocktail Shaker Sort | |
|---|---|---|
| Average time | O(n²) | O(n²) |
| Worst time | O(n²) | O(n²) |
| Space | O(1) | O(1) |
| Stable | Yes | Yes |
When to use Insertion Sort
Small arrays or nearly-sorted arrays. O(n) best case for already-sorted input. Used as a subroutine in Timsort.
When to use Cocktail Shaker Sort
Teaching, or small arrays where small values sit near the end (where plain Bubble Sort is slow).