Skip to content
Related Articles

Related Articles

Python Program for Insertion Sort

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 19 Sep, 2022
View Discussion
Improve Article
Save Article

Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. 

Python




# Python program for implementation of Insertion Sort
 
# Function to do insertion sort
def insertionSort(arr):
 
    # Traverse through 1 to len(arr)
    for i in range(1, len(arr)):
 
        key = arr[i]
 
        # Move elements of arr[0..i-1], that are
        # greater than key, to one position ahead
        # of their current position
        j = i-1
        while j >=0 and key < arr[j] :
                arr[j+1] = arr[j]
                j -= 1
        arr[j+1] = key
 
 
#sorting the array [12, 11, 13, 5, 6] using insertionSort
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
lst = [] #empty list to store sorted elements
print("Sorted array is : ")
for i in range(len(arr)):
    lst.append(arr[i])     #appending the elements in sorted order
print(lst)
 
 
# This code is contributed by Mohit Kumra

Output:

Sorted array is:
[5, 6, 11, 12, 13]

Time Complexity: O(N2
Auxiliary Space: O(1)

Please refer complete article on Insertion Sort for more details!

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!