Insertion Sort vs Heap Sort
Across our 3 test inputs, Insertion Sort needed 85 comparisons in total versus 112 for Heap Sort. On average Insertion Sort runs in O(n²) time and Heap Sort in O(n log n). Insertion Sort is stable; Heap Sort is not.
Head-to-head on identical inputs (comparisons)
| Input | Insertion Sort | Heap Sort |
|---|---|---|
| Random order | 30 | 36 |
| Nearly sorted | 10 | 41 |
| Reversed | 45 | 35 |
Complexity
| Insertion Sort | Heap Sort | |
|---|---|---|
| Average time | O(n²) | O(n log n) |
| Worst time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
| Stable | Yes | No |
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 Heap Sort
When you need guaranteed O(n log n) with O(1) extra memory — e.g. embedded or real-time systems.