Kodewick
Start learning →

Insertion sort in Python, visualized step by step

PythonC

Like sorting playing cards in your hand: the left part is sorted; take the next card, shift every bigger card one place right, and put it into the gap.

insertion_sort.py
nums = [7, 3, 5, 1, 6]
for i in range(1, len(nums)):
    key = nums[i]
    j = i - 1
    while j >= 0 and nums[j] > key:
        nums[j + 1] = nums[j]
        j -= 1
    nums[j + 1] = key
print(nums)
Press ▶ to play, or ‹ › to stepEdit this code in the online compiler ↗

How Insertion sort works

  1. Starting from the second value, take it out as key.
  2. Compare it with the sorted values from right to left; shift each bigger one right.
  3. At a value not bigger than key (or the start), put key in the gap.
  4. Move on to the next value and repeat.

What to watch

keyThe value taken out: watch where it lands.
j moving leftBigger values shift right one by one to make room for key.

FAQ

What is the time complexity of insertion sort?

O(n²) in the worst and average case, but only O(n) when the input is almost sorted: that is its big strength.

Is insertion sort stable?

Yes. Only values strictly greater than key are shifted, so equal values keep their order.

Is insertion sort used in practice?

Yes. It is fast for small or nearly sorted inputs; Python's sorted() (Timsort) uses it on short runs.

More algorithms

All 10 algorithm visualizations →