In this tutorial, you will learn how the insertion sort algorithm works. Also, you will find working examples of insertion sort in Python. Before we get started, if you want to about the bubble sort algorithm, please go through the article.
Introduction to Insertion Sort Algorithm
In the same way, other unsorted cards are taken and put in the right place. A similar approach is used by insertion sort. Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration. Please see the following picture:
How does the Insertion Sort Algorithm work?
Suppose we need to sort the following array.
- The first element in the array is assumed to be sorted. Take the second element and store it separately in key. Compare the key with the first element. If the first element is greater than, then the key is placed in front of the first element. If the first element is greater than the key, then the key is placed in front of the first element.
- Now, the first two elements are sorted. Take the third element and compare it with the elements on the left of it. Placed it just behind the element smaller than it. If there is no element smaller than it, then place it at the beginning of the array.
- Similarly, place every unsorted element at its correct position.
Insertion Sort Algorithm
mark first element as sorted
for each unsorted element X
'extract' the element X
for j <- lastSortedIndex down to 0
if current element j > X
move sorted element to the right by 1
break loop and insert X here
# Insertion sort in Python
for step in range(1, len(array)):
key = array[step]
j = step - 1
# Compare key with each element on the left of it until an element smaller than it is found
# For descending order, change key<array[j] to key>array[j].
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j = j - 1
# Place key at after the element just smaller than it.
array[j + 1] = key
data = [9, 5, 1, 4, 3]
print('Sorted Array in Ascending Order:')
- Worst Case Complexity: O(n2)
Suppose, an array is in ascending order, and you want to sort it in descending order. In this case, the worst-case complexity occurs. Each element has to be compared with each of the other elements so, for every nth element, (n-1) a number of comparisons are made. Thus, the total number of comparisons = n*(n-1) ~ n2
- Best Case Complexity: O(n)
When the array is already sorted, the outer loop runs for n number of times whereas the inner loop does not run at all. So, there is only n number of comparisons. Thus, complexity is linear.
- Average Case Complexity: O(n2)
It occurs when the elements of an array are in jumbled order (neither ascending nor descending).
- Space complexity is O(1) because an extra variable key is used.
Insertion Sort Applications
The insertion sort is used when:
- the array is has a small number of elements
- there are only a few elements left to be sorted