Interactive demo

Insertion Sort Visualization

Insertion sort works like sorting playing cards in your hand: it takes one element after the other and inserts it into the sorted part at the right place. It is very fast on nearly sorted arrays.

Your browser does not support the HTML5 canvas tag.

Try “Nearly sorted”: only a few elements have to move. “Reversed” is the worst case.

Playback

Comparisons
0
Writes
0

Array

Legend

  • Unsorted element
  • Sorted part
  • Element being inserted
  • Compared element
  • Final position

Runtime and properties

Best case

O(n)

Already sorted: every element only needs one comparison to stay where it is.

Average case

O(n²)

On average every element shifts past half of the sorted part.

Worst case

O(n²)

Reversed order: every element has to shift past the whole sorted part.

Extra memory

O(1)

Only the element being inserted is held aside.

Stable

Yes

Elements shift only past larger ones, never past equal ones.

In-place

Yes

Elements are shifted within the array.

n is the number of elements. O(n log n) is the best a sorting algorithm based on comparisons can achieve.

Compared with the other sorting algorithms

AlgorithmBest caseAverage caseWorst caseExtra memoryStableIn-place
Bubble sortO(n)O(n²)O(n²)O(1)YesYes
Selection sortO(n²)O(n²)O(n²)O(1)NoYes
Insertion sort this pageO(n)O(n²)O(n²)O(1)YesYes
Shell sortO(n log n)≈ O(n1.25)O(n1.5)O(1)NoYes
Tree sortO(n log n)O(n log n)O(n²)O(n)YesNo
Tournament sortO(n log n)O(n log n)O(n log n)O(n)YesNo
HeapsortO(n log n)O(n log n)O(n log n)O(1)NoYes
SmoothsortO(n)O(n log n)O(n log n)O(1)NoYes
Merge sortO(n log n)O(n log n)O(n log n)O(n)YesNo
Patience sortO(n)O(n log n)O(n log n)O(n)YesNo
TimsortO(n)O(n log n)O(n log n)O(n)YesNo
Block sortO(n)O(n log n)O(n log n)O(1)YesYes
QuicksortO(n log n)O(n log n)O(n²)O(log n)NoYes
IntrosortO(n log n)O(n log n)O(n log n)O(log n)NoYes
FluxsortO(n)O(n log n)O(n log n)O(n)YesNo
CrumsortO(n)O(n log n)O(n log n)O(log n)NoYes

1. Take an element out

The sorted part starts with the first element. The next element is taken out, which leaves a gap in the array.

2. Shift larger elements

Going left through the sorted part, every larger element is shifted one place to the right into the gap. The gap moves left with it.

3. Insert

At the first element that is not larger, the taken element drops into the gap. On nearly sorted arrays this happens almost immediately, which is why many fast sorting algorithms use insertion sort for small parts.