Algorithms · Visualized
Insertion Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Insertion Sort builds the sorted array one element at a time, the same way you'd sort playing cards in your hand — you pick up the next card and slide it into its correct place among the cards you're already holding. Time: O(n²) average, O(n²) worst; space: O(1) — sorts in place.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Insertion Sort
SortingInsertion Sort builds the sorted array one element at a time, the same way you'd sort playing cards in your hand — you pick up the next card and slide it into its correct place among the cards you're already holding.
How Insertion Sort Works
- Start from the second element (index 1); treat the first element as a sorted list of size one.
- Take the current element and compare it backwards against the sorted part.
- Shift every element that is bigger than the current element one place to the right.
- Insert the current element into the gap left behind.
- Move to the next element and repeat until the whole array is processed.
Insertion Sort Worked Example
Input: [12, 11, 13, 5, 6]
Take 11: shift 12 right, insert 11 → [11,12,13,5,6]. Take 13: already bigger than 12, stays → [11,12,13,5,6]. Take 5: shift 13,12,11 right, insert 5 at front → [5,11,12,13,6]. Take 6: shift 13,12,11 right, insert 6 after 5 → [5,6,11,12,13]. Sorted.
def insertion_sort(a):
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Insertion Sort Time & Space Complexity
When to Use Insertion Sort
- Small arrays, or arrays that are already almost sorted (very fast in that case).
- Used as the final finishing step inside faster hybrid sorts like Timsort and introsort.
- Online sorting, where data arrives one item at a time and must stay sorted.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.