The Wayback Machine - https://web.archive.org/web/20230601103458/https://www.geeksforgeeks.org/python-program-for-insertion-sort/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python Program for Insertion Sort

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like 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):
     
    if (n := len(arr)) <= 1:
      return
    for i in range(1, n):
         
        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)
print(arr)

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
Last Updated : 19 Dec, 2022
Like Article
Save Article
Similar Reads