Skip to content
SimpleScope

Sorting

Selection sort vs Insertion sort

Selection sort and Insertion sort both put an array in order, in different ways. Selection sort: repeatedly pick the smallest remaining value. Insertion sort: insert each value into a sorted prefix. In the worst case both take O(n²), so the choice comes down to the other differences below.

At a glance

PropertySelection sortInsertion sort
TechniqueRepeatedly pick the smallest remaining valueInsert each value into a sorted prefix
Best case timeO(n²)O(n)
Average case timeO(n²)O(n²)
Worst case timeO(n²)O(n²)
Extra spaceO(1)O(1)
Stable (equal values keep their order)NoYes
In place (no extra array)YesYes
Needs sorted inputNoNo

When to choose each

Choose selection sort when

writing to memory is expensive, since it makes at most n - 1 swaps.

Avoid it when

the data is large, or you hope sorted input will be fast.

Choose insertion sort when

the array is small or nearly sorted.

Avoid it when

the array is large and in random order.

The same inputs, counted

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

InputSelection sortInsertion sort
Mixed2930
Already sorted2112
Reversed2748
Nearly sorted2314
Duplicates3136

See them run

More comparisons