key
shifting
sorted
5
0
3
1
8
2
1
3
9
4
2
5
7
6
4
7
Pick each element and insert it into the correct position in the sorted portion.
Think of sorting cards — pick one and slide it left until it's in the right place.
start
1 / 64
SPD0.5×
click to pause · hover for controls · fullscreen for more

Insertion Sort

Builds a sorted list one element at a time

Visual by thisgirltech

BeginnerSorting

Insertion sort works exactly the way you sort a hand of playing cards — you pick up one card at a time and slide it left until it lands in the right position among the cards you already hold.

The animation shows this directly. Everything to the left of the yellow bar is already sorted. The yellow bar is the element being inserted. As it scans left, larger elements are shown in orange as they shift one step right to make room.

This makes the algorithm easy to watch: the green sorted region grows by one element every round, and the shifting shows exactly why insertion sort costs O(n²) — in the worst case every single element needs to travel all the way to the left edge.

In-place sorting

Insertion sort rearranges the original array using only a single temporary variable for the key being inserted. No extra array is allocated — space complexity is O(1).

Excellent on small or nearly-sorted data

If the array is already almost sorted, the inner while loop barely runs. Best case is O(n) — each element just checks its left neighbour and stays put.

Stable sort

Equal elements are never moved past each other — insertion sort places the new element after any equal elements already in the sorted region. Original relative order is preserved.

Used inside faster algorithms

Timsort (used in Python and Java) switches to insertion sort for sub-arrays smaller than ~64 elements, because insertion sort has very low overhead on small inputs.

TIP

Pause on a SHIFTING step and count how many orange bars move right. Each shift is one unit of work. For a completely reversed array, the total shifts equal n*(n-1)/2 — that is where O(n²) comes from.

COLOUR LEGEND

Picked up
Comparing
Shifting
Sorted region
Unsorted