PUBLISHED ON: AUGUST 17, 2021
Python program for Recursive Insertion Sort
The method of defining something in terms of itself is referred to as the recursive method. In this tutorial, we will perform recursive insertion sort operation to sort an array.
Algorithm for Recursive Insertion Sort
We have already seen the insertion sort operation with the simple method and we have basic knowledge on how sorting is done but recursive insertion sort is different let's have a look at the Algorithm followed by the code:
- Create a function insertion_sort()
- Declare the function with two parameters
- The first parameter will be the array
- The second parameter will be the length
- Iterate through element [1] to element [n-1]
- Compare the element [i]
- Put it at a suitable index in the array
- The array is now sorted
- Print the sorted array
Program
As discussed above in the algorithm, let us now dive into the programming part of the Recursive Insertion Sort operation influenced by the algorithm.
def insertion_sort(arr, Len):
if Len <= 1:
return
insertion_sort(arr, Len - 1)
end = arr[Len - 1]
i = Len - 2
while(i>=0 and arr[i] > end):
arr[i+1] = arr[i]
i = i - 1
arr[i + 1] = end
array = [9, 1, 7, 3, 5]
print("The Original array is: ", array)
insertion_sort(array, len(array))
print("The Sorted array is :", array)
The Original array is: [9, 1, 7, 3, 5]
The Sorted array is : [1, 3, 5, 7, 9]
Conclusion
In this tutorial, we have performed an Insertion sorting operation in python programming to sort an array. The time complexity of recursive insertion sort is O(n) and the space complexity is O(1).