Skip to content
Related Articles

Related Articles

Improve Article

Python Program for Recursive Insertion Sort

  • Difficulty Level : Medium
  • Last Updated : 30 Dec, 2020

Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
Below is an iterative algorithm for insertion sort


// Sort an arr[] of size n
insertionSort(arr, n) 
    Loop from i = 1 to n-1.
       a) Pick element arr[i] and insert
          it into sorted sequence arr[0..i-1] 


# Recursive Python program for insertion sort
# Recursive function to sort an array using insertion sort
def insertionSortRecursive(arr,n):
    # base case
    if n<=1:
    # Sort first n-1 elements
    \'\'\'Insert last element at its correct position
        in sorted array.\'\'\'
    last = arr[n-1]
    j = n-2
      # Move elements of arr[0..i-1], that are
      # greater than key, to one position ahead
      # of their current position 
    while (j>=0 and arr[j]>last):
        arr[j+1] = arr[j]
        j = j-1
# A utility function to print an array of size n
def printArray(arr,n):
    for i in range(n):
        print arr[i],
# Driver program to test insertion sort 
arr = [12,11,13,5,6]
n = len(arr)
insertionSortRecursive(arr, n)
printArray(arr, n)
# Contributed by Harsh Valecha

Please refer complete article on Recursive Insertion Sort for more details!

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up
Recommended Articles
Page :