Python Program for Recursive Insertion Sort
Recursive Insertion Sort is a variation of the standard Insertion Sort algorithm that uses recursion instead of iterative loops. It sorts an array by recursively sorting smaller portions of the array and inserting each element into its correct position in the sorted part.
Algorithm
Treat the first n-1 elements as a smaller subproblem - sort them recursively - and then insert the nth element into the correct position among them. This process continues until the array is fully sorted. Below is the step-by-step guide:
- If the array size n <= 1, it is already sorted (base case).
- Recursively call the function to sort the first n-1 elements.
- Store the last element (the nth element) in a temporary variable last.
- Shift all elements greater than last one position ahead.
- Insert last into its correct position.
- Repeat this process until the entire array is sorted.
def ins_sort(arr, n):
if n <= 1:
return
ins_sort(arr, n - 1)
last = arr[n - 1]
j = n - 2
while j >= 0 and arr[j] > last:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = last
a = [-7, 11, 6, 0, -3, 5, 10, 2]
ins_sort(a, len(a))
print(a)
Output
[-7, -3, 0, 2, 5, 6, 10, 11]
Explanation:
- def ins_sort(arr, n): defines the recursive insertion sort function.
- if n <= 1: acts as the base case — a single element is already sorted.
- ins_sort(arr, n - 1) sorts the first n-1 elements recursively.
- last = arr[n - 1] stores the element to be inserted.
whileloop shifts elements greater thanlastto the right.arr[j + 1] = lastinsertslastin its correct position.