Visualizing Insertion Sort

1. The Core Idea

Insertion Sort works similarly to how you would organize playing cards in your hand.

It splits the collection conceptually into a sorted subset on the left and an unsorted subset on the right.

Initially, the first element (index $0$) is sorted by default because a single-element list is always sorted.

2. The "Key" Element

For each position, we pick the first unsorted item as our Key (highlighted in pink).

We extract this Key and scan the sorted items to its left, moving right-to-left, looking for where this Key belongs.

Here, the Key is $2$. Since $2 < 5$, the Key is smaller and must find a place before $5$. We must make space.

3. Shifting Elements Right

To insert our Key, any sorted item that is larger than the Key must be shifted one position to the right.

This shifting sequence clears an available slot near the beginning of the list.

The value $5$ shifts into the position previously occupied by $2$, creating an opening at index $0$.

4. Inserting the Key

Once all larger elements are shifted, we insert the Key into its correct destination slot.

With $2$ successfully placed at index $0$, our sorted subset grows to encompass $[2, 5]$.

5. Live Algorithm Simulator

Step through or play the complete algorithm to watch insertion sort build order on custom patterns.

for i = 1 to n-1
key = A[i]
j = i - 1
while j ≥ 0 and A[j] > key
A[j+1] = A[j]
j = j - 1
A[j+1] = key
State: 0 / 0
Ready to sort.