Skip to content
SimpleScope

Sorting

Insertion sort vs Heap sort

Insertion sort and Heap sort both put an array in order, in different ways. Insertion sort: insert each value into a sorted prefix. Heap sort: build a max-heap in the array, then repeatedly move the largest value to the end. In the worst case heap sort takes O(n log n) while insertion sort takes O(n²), so heap sort scales better on large inputs.

At a glance

PropertyInsertion sortHeap sort
TechniqueInsert each value into a sorted prefixBuild a max-heap in the array, then repeatedly move the largest value to the end
Best case timeO(n)O(n log n)
Average case timeO(n²)O(n log n)
Worst case timeO(n²)O(n log n)
Extra spaceO(1)O(1)
Stable (equal values keep their order)YesNo
In place (no extra array)YesYes
Needs sorted inputNoNo

When to choose each

Choose insertion sort when

the array is small or nearly sorted.

Avoid it when

the array is large and in random order.

Choose heap sort when

you need a guaranteed O(n log n) time and almost no extra memory.

Avoid it when

you need a stable sort, or the fastest sort on typical data.

The same inputs, counted

These numbers come from running both real implementations: operations (comparisons plus writes, a swap counting as two writes).

InputInsertion sortHeap sort
Mixed3043
Already sorted1253
Reversed4840
Nearly sorted1450
Duplicates3636

See them run

More comparisons