Selection Sort vs Insertion Sort
Across our 3 test inputs, Insertion Sort needed 85 comparisons in total versus 135 for Selection Sort. Insertion Sort is stable; Selection Sort is not.
Head-to-head on identical inputs (comparisons)
| Input | Selection Sort | Insertion Sort |
|---|---|---|
| Random order | 45 | 30 |
| Nearly sorted | 45 | 10 |
| Reversed | 45 | 45 |
Complexity
| Selection Sort | Insertion Sort | |
|---|---|---|
| Average time | O(n²) | O(n²) |
| Worst time | O(n²) | O(n²) |
| Space | O(1) | O(1) |
| Stable | No | Yes |
When to use Selection Sort
When memory writes are expensive (minimizes swaps). Otherwise, insertion sort is generally preferred.
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.