Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Visualizer › Sorting

Insertion Sort

Builds a sorted part on the left and inserts each next element into its correct place, like sorting playing cards in your hand.

How it works

Complexity

Code (Python)

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]   # shift right
            j -= 1
        a[j + 1] = key
    return a

Practise: Arrays problems