Python: Insertion sort
6. Insertion Sort
Write a Python program to sort a list of elements using the insertion sort algorithm.
Note: According to Wikipedia "Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort."
Pictorial Presentation: Insertion Sort
 
Sample Solution:
Python Code:
def insertionSort(nlist):
   for index in range(1,len(nlist)):
     currentvalue = nlist[index]
     position = index
     while position>0 and nlist[position-1]>currentvalue:
         nlist[position]=nlist[position-1]
         position = position-1
     nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)
Sample Output:
[14, 21, 27, 41, 43, 45, 46, 57, 70]
Flowchart :
 
For more Practice: Solve these Related Problems:
- Write a Python program to implement insertion sort and display the list after inserting each element.
- Write a Python script to sort a list of strings using insertion sort and then print the sorted list.
- Write a Python program to use insertion sort to sort a list of numbers and count the number of shifts required.
- Write a Python function to perform insertion sort on a list of floating-point numbers and then verify the sorted order.
Go to:
Previous:  Write a Python program to sort a list  of elements using the selection  sort algorithm.
  Next:  Write a Python program to sort a list  of elements using shell sort algorithm.
Python Code Editor :
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
