Start free

Advanced · Sorting algorithms · 170 of 264

Insertion sort, step by step

Insertion sort: take each number from the second one on and move it left until it is in place. Print the list after each number is inserted.

Input: whole numbers on one line (at least 2). Output: the list after each insertion.

Examples

Input
3 1 2
Output
1 3 2
1 2 3
Input
1 2 3
Output
1 2 3
1 2 3
Input
4 3 2 1
Output
3 4 2 1
2 3 4 1
1 2 3 4

One more test checks other inputs when you press Check.

Stuck? The idea behind sorting algorithms

Bubble sort swaps neighbours that are in the wrong order, pass after pass. Insertion sort takes each item in turn and slides it back into place among those before it. Merge sort splits the list, sorts each half and merges them.

These exercises ask for the steps, not just the result: write the algorithm yourself rather than calling sorted().

a = [5, 1, 4, 2]
for end in range(len(a) - 1, 0, -1):
    for i in range(end):
        if a[i] > a[i + 1]:
            a[i], a[i + 1] = a[i + 1], a[i]
print(a)

Watch for: Off-by-one: comparing a[i] with a[i + 1] means i must stop one before the end.

All the sorting algorithms exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More sorting algorithms exercises