Insertion Sort Program in Python
Python - Insertion Sort
In the tutorial, we will implement Insertion Sort Algorithm in Python.
We will write a function named insertion_sort() which takes list as argument and sorts this list using Insertion Sort algorithm. Also, by default, this insertion_sort() function sorts the list in ascending order. To get the descending order, all you have to do is just reverse the list.
Python Program
def insertion_sort(nlist):
for i in range(1, len(nlist)):
temp = nlist[i]
j = i - 1
while (j >= 0 and temp < nlist[j]):
nlist[j + 1] = nlist[j]
j = j - 1
nlist[j + 1] = temp
#input list
alist = [1, 74, 96, 5, 42, 63]
print('Input List\n', alist)
#sort list
insertion_sort(alist)
print('Sorted List\n', alist)
Output
Input List
[1, 74, 96, 5, 42, 63]
Sorted List
[1, 5, 42, 63, 74, 96]
Conclusion
In this tutorial of Python Examples, we learned how to implement Insertion Sort algorithm in Python.