← Back to cc

Insertion Sort in Python

Learn about Insertion Sort, a sorting method for arrays

BeginnerSortingArraysPython

Sorting Algorithms

For all examples, assume a dummy array, like x = [-5,-3,2,1,-3,-3,7,2,2] This could be any array, but this is simply an example to work with. We are sorting this array in ASCENDING order.

Insertion Sort

The idea behind this sort is that you have a sorted part of the array, and a unsorted part. You take elements from the unsorted part and put them in their respective spots in the sorted part of the array.

Example:

Algorithm:

Complexity:

Python code for insertion sort:

x = [-5,-3,2,1,-3,-3,7,2,2, -9] # dummy array 


for i in range(1,len(x)): # for every element that's UNSORTED(always assume first one is)
    for j in range(i,0,-1): # go backwards from the current index to the start of the array
            if(x[j]<x[j-1]): # if the current index is smaller than the one before
                x[j],x[j-1] = x[j-1],x[j] # switch
            else:
                break # go to next element
            
print(x)