Insertion sort in Python
Published: 2024-04-15 01:16:26

---
title: Insertion sort in Python
published: true
date: 
tags: 
series: sorting
canonical_url: https://www.pynerds.com/data-structures/implement-insertion-sort-in-python/
---
Insertion sort is a simple yet relatively efficient comparison-based sorting algorithm.

Compared to other basic sorting algorithm such as [bubble sort](https://www.pynerds.com/data-structures/implement-bubble-sort-algorithm-in-python/)and [selection sort](https://www.pynerds.com/data-structures/implement-selection-sort-in-python/),  insertion sort  performs relatively well especially  on small-to-medium and **mostly sorted** lists. It also has a stable sorting behavior, meaning that elements with equal values will maintain their original relative order after sorting.

Insertion sort works in-place, in that it re-arranges the elements of the original list instead of creating a new list. This makes it efficient in terms of memory usage.

Compared to other advanced sorting algorithm such as `quicksort `and `mergesort`, insertion sort is relatively easy to understand and implement. However it has an average and  worst-time complexities of` O(n2)`, this means that it can be inefficient when sorting large dataset. It works well when the input list is small in size and or it is nearly sorted.

## Algorithm Description

In insertion sort, the input array/list is divided into two segments, the **sorted segment**  on the left and the **unsorted segment ** on the right. Initially, the sorted segment is made up of only the first element of the list, while the unsorted segment is made up of the rest of the list elements.

The algorithm iterates through the unsorted segment and takes one element at a time, comparing it with the elements in the sorted segment. It finds the correct position for the element in the sorted segment and **inserts** it there, shifting the other elements if necessary. The process continues until all elements in the unsorted segment are inserted into their correct positions in the sorted segment.

The following is the higher-level description of the steps in the insertion sort algorithm:

1. The first element is already sorted.
2. Pick the  next element.
3. Compare it with the the elements in the sorted segment.
4. Insert it before all larger elements.
5. Repeat **steps 2-4** with the rest of the unsorted elements until the entire list is sorted. 

### Insertion sort Example

In this part we will demonstrate the steps insertion sort algorithm would follow to sort the following  list.

![Unsorted list](https://res.cloudinary.com/dgc50iktu/image/upload/v1713132612/9d7929d6-c262-4a60-9416-6d750bba8a64_-_Copy_tdb8um.png)

In the first step the sorted segment is only made up of the first element of the list. Logically, a list with only one item is already sorted.

![the sorted segment is made up of only the first item in the list.](https://res.cloudinary.com/dgc50iktu/image/upload/v1713132612/45a6f035-9c7e-4c92-bd37-4b00dbcc7d1f_-_Copy_wvma02.png)

We will use color green to indicate the elements in the sorted segment and red for element in the unsorted segment.

We start by picking an unsorted element and placing it at its position in the sorted segment. The first unsorted element is `4`, so we pick it and insert it at its place in the sorted segment.

![Pick the first element in the unsorted segment and place it in the sorted segment.](https://res.cloudinary.com/dgc50iktu/image/upload/v1713132611/6d3f658b-d10d-4c16-8cdb-3e6a8f34103d_eicy7q.png)

In the above  case, `4` is smaller than` 7` so the two are swapped. We now move on to the next unsorted element which is `8`.

![8 is already sorted.](https://res.cloudinary.com/dgc50iktu/image/upload/v1713132612/Insertion_3_-_Edited_-_Copy_ld5tf6.png) 

In the above case, we found that `8` is already sorted so no need for performing any action.

![Insert 5 at its place](https://res.cloudinary.com/dgc50iktu/image/upload/v1713132611/df6d55ca-5be0-4cd8-bf04-00dc3aa10934_tcecge.png) 

After placing `5` at its place, the unsorted segment is now only made up of a single element, `6`. let us put it in its place.

![The final step of insertion sort](https://res.cloudinary.com/dgc50iktu/image/upload/v1713132611/1799806d-f397-4e80-bff2-42477690b576_d3zpfs.png)

After performing the above step, we are done and the list is now sorted.

## Insertion sort implementation.

We can implement insertion sort through nested loops. the first loop picks the current unsorted element and the inner loop inserts it at its place in the sorted segment. The most suitable approach of implementing this is by use of an outer [for loop](https://www.pynerds.com/python-for-loops/)and an inner [while loop](https://www.pynerds.com/python-while-loop/).

```

def insertion_sort(lst):

   for i in range(1, len(lst)):
      j = i
      while (j > 0) and lst[j-1] > lst[j]:
         lst[j-1], lst[j] = lst[j], lst[j-1] #swap the elements
         j -=1

#sort a list
L = [99, 9, 0, 2, 1, 0, 1, 100, -2, 8, 7, 4, 3, 2]

insertion_sort(L)
print("The sorted list is: ", L)
```

The `insertion_sort()` function above, does not return any value because the input list is being sorted **in-place**.

`For `loops are useful when we know in advance the number of iterations needed  and in contrast, `while` loops are more suitable in cases where we do not know in advance the number of iterations to be performed. The fitness of each of the two loops is clearly shown in the above implementation of insertion sort.  Using an inner `while `loop ensures that we can efficiently get out of the loop after the element is placed at its position without using extra conditional checks. 

### Descending insertion sort

To sort the list elements in descending order using insertion sort, we simply need to change a single statement in the `insertion_sort()` function and actually just a single character.

Changing the `>` character in the second condition of the while loop to` <` character will make the algorithm to sort the elements in descending order i.e we need to change the statement from`  while (j > 0) and lst[j-1] > lst[j]:` to  `while (j > 0) and lst[j-1] < lst[j]:`.

descending insertion sort

```

def insertion_sort(lst):

   for i in range(1, len(lst)):
      j = i
      while (j > 0) and lst[j-1] < lst[j]: #changed > to <
         lst[j-1], lst[j] = lst[j], lst[j-1] #swap the elements
         j -=1

#sort a list
L = [99, 9, 0, 2, 1, 0, 1, 100, -2, 8, 7, 4, 3, 2]

insertion_sort(L)
print("The sorted list is: ", L)
```

## Algorithm analysis

The running time complexities of insertions sort are as shown below:

- **best case - ** `O(n)`, this is when the list is already sorted.
- **Average case ** - `O(n2)`, this is when the list is randomly sorted.
- **Worst case** - `O(n2`), When the list is reverse sorted.

## Applications of insertion sort

The following list outlines cases where insertion sort may be suitable:

- When the dataset is not very large in size.
- When the elements are almost sorted.
- When simplicity and stability are needed.

Insertion sort is relatively more performant compared to other basic sorting algorithm such as bubble sort or selection sort. However, its` O(n2)`  average and worst running time makes it limited compared to other sorting algorithms such as **quicksort** or **mergesort**. It is, therefore, more suitable when sorting small sets of data.
<div class="related"><h3>Related articles</h3><hr><ul><li><p><a class="text-success" href="https://www.pynerds.com/data-structures/implement-stack-data-structure-in-python/">Implement Stack data structure in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/data-structures/implement-queue-data-structure-in-python/">Implement Queue data structure in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/data-structures/implement-fixed-length-stack-in-python/">Implement Fixed-length stack in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/data-structures/double-ended-queue-in-python/">Double-ended Queue in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/data-structures/doubly-linked-list-in-python/">Doubly-Linked List in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/data-structures/implement-inorder-tree-traversal-python/">Implement Inorder Tree Traversal - Python</a><li><p><a class="text-success" href="https://www.pynerds.com/data-structures/implement-bubble-sort-algorithm-in-python/">Implement bubble sort algorithm in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/data-structures/implement-selection-sort-in-python/">Implement selection sort in Python</a></ul></div>