Learn Python – Insertion Sort in Python- Basic and advance

The Insertion type is a straightforward and extra environment friendly algorithm than the preceding bubble type algorithm. The insertion sort algorithm notion is based on the deck of the card the place we kind the playing card according to a unique card. It has many advantages, however there are many efficient algorithms accessible in the records structure.

While the card-playing, we compare the fingers of cards with each other. Most of the participant likes to sort the card in the ascending order so they can rapidly see which combinations they have at their disposal.

The insertion sort implementation is easy and simple because it’s generally taught in the commencing programming lesson. It is an in-place and secure algorithm that is more advisable for nearly-sorted or fewer elements.

The insertion sort algorithm is not so quickly due to the fact of it uses nested loop for sort the elements.

Let’s understand the following terms.

What is the meaning of in-place and stable?

In-place: The in-place algorithm requires additional space without caring for the input size of the collection. After performing the sorting, it rewrites the original memory locations of the elements in the collection.

Stable: The stable is a term that manages the relative order of equal objects from the initial array.

The extra important thing, the insertion sort does not require to know the array size in improve and it receives the one aspect at a time.

The tremendous thing about the insertion type is if we insert the more elements to be sorted – the algorithm arranges the in its acceptable vicinity except performing the entire sort.

It is extra efficient for the small (less than 10) measurement array. Now, let’s understand the ideas of insertion sort.

The Concept of Insertion Sort

The array spilled genuinely in the two parts in the insertion type – An unsorted section and sorted part.

The sorted phase incorporates the first factor of the array and other unsorted subpart includes the rest of the array. The first issue in the unsorted array is compared to the sorted array so that we can place it into a acceptable sub-array.

It focuses on inserting the factors with the aid of shifting all factors if the right-side value is smaller than the left side.

It will over and over occur until the all thing is inserted at correct place.

To type the array using insertion kind below is the algorithm of insertion sort.

Spilt a list in two parts – sorted and unsorted.

Iterate from arr[1] to arr[n] over the given array.

Compare the current element to the next element.

If the current element is smaller than the next element, compare to the element before, Move to the greater elements one position up to make space for the swapped element.

Let’s understand the following example.

We will reflect onconsideration on the first component in the sorted array in the following array.

[10, 4, 25, 1, 5]

The first step to add 10 to the sorted subarray

[10, 4, 25, 1, 5]

Now we take the first component from the unsorted array – four We store this price in a new variable temp. Now, we can see that the 10>4 then we go the 10 to the proper and that overwrite the four that was beforehand stored.

[10, 10, 25, 1, 5] (temp = 4)

Here the four is lesser than all factors in sorted subarray, so we insert it at the first index position.

[4, 10, 25, 1, 5]

We have two elements in the sorted subarray.

Now test the variety 25. We have saved it into the temp variable. 25> 10 and also 25> 4 then we put it in the third role and add it to the sorted sub array.

[4, 10, 25, 1, 5]

Again we test the quantity 1. We keep it in temp. 1 is less than the 25. It overwrites the 25.

[4, 10, 25, 25, 5] 10>1 then it overwrites again

[4, 25, 10, 25, 5]

[25, 4, 10, 25, 5] 4>1 now put the price of temp = 1

[1, 4, 10, 25, 5]

Now, we have 4 elements in the sorted subarray. 5<25 then shift 25 to the proper facet and skip temp = 5 to the left side.

[1, 4, 10, 25, 25] put temp = 5

Now, we get the sorted array with the aid of simply inserting the temp value.

[1, 4, 5, 10, 25]

The given array is sorted.


The implementation of insertion is relative easy. We will implement the use of the Python array of integers. Let’s understand the following instance –

Python Program

# creating a function for insertion  
def insertion_sort(list1):  
        # Outer loop to traverse through 1 to len(list1)  
        for i in range(1, len(list1)):  
            value = list1[i]  
            # Move elements of list1[0..i-1], that are  
            # greater than value, to one position ahead  
            # of their current position  
            j = i - 1  
            while j >= 0 and value < list1[j]:  
                list1[j + 1] = list1[j]  
                j -= 1  
            list1[j + 1] = value  
        return list1  
            # Driver code to test above  
list1 = [10, 5, 13, 8, 2]  
print("The unsorted list is:", list1)  
print("The sorted list1 is:", insertion_sort(list1))  


The unsorted list is: [10, 5, 13, 8, 2]
The sorted list1 is: [2, 5, 8, 10, 13]


In the above code, we have created a characteristic referred to as insertion_sort(list1). Inside the function –

We defined for loop for traverse the list from 1 to len(list1).

In for loop, assigned a values of list1 in value Every time the loop will iterate the new value will assign to the value variable.

Next, we moved the elements of list1[0…i-1], that are greater than the value, to one position ahead of their current position.

Now, we used the while to check whether the j is greater or equal than 0, and the value is smaller than the first element of the list.

If both conditions are true then move the first element to the 0th index and reduce the value of j and so on.

After that, we called the function and passed the list and printed the result.

Sorting Custom Objects

Python gives the flexibility to trade the algorithm the use of a customized object. We will create a custom category and redefine the real assessment parameter and strive to preserve the same code as the above.

We would require to overload the operators in order to type the objects in a distinct way. But, we can skip some other argument to the insertion_sort() feature with the aid of the usage of the lambda function. The lambda feature is a handy when calling the sorting method.

Let’s apprehend the following example of sorting customized objects.

First, we are defining the Point class:

Python Program

# Creating Point class  
class Point:  
    def __init__(self, a, b):  
        self.a = a  
        self.b = b  
    def __str__(self):  
        return str.format("({},{})", self.a, self.b)  
def insertion_sort(list1, compare_function):  
    for i in range(1, len(list1)):  
        Value = list1[i]  
        Position = i  
        while Position > 0 and compare_function(list1[Position - 1], Value):  
            list1[Position] = list1[Position - 1]  
            PositionPosition = Position - 1  
        list1[Position] = Value  
U = Point(2,3)  
V = Point(4,4)  
X = Point(3,1)  
Y = Point(8,0)  
Z = Point(5,2)  
list1 = [U,V,X,Y,Z]  
# We sort by the x coordinate, ascending  
insertion_sort(list1, lambda x, y: x.a > y.a)  
for point in list1:  


The points are in the sorted order

Using the above code, we can sort the coordinate points. It will work for any kind of the list.

Time Complexity in Insertion Sort

Insertion sort is a sluggish algorithm; sometimes, it appears too sluggish for vast dataset. However, it is efficient for small lists or array.

The time complexity of the insertion kind is – O(n2). It makes use of the two loops for iteration.

Another vital benefit of the insertion type is that; it is used through the famous sorting algorithm referred to as Shell sort.

The auxiliary space in insertion sort: O(1)


Insertion kind is a simple and inefficient algorithm that has many advantages, but there are more environment friendly algorithms are available.

In this tutorial, we have mentioned the idea of the insertion sort and its implementation using the Python programming language.