Python Program for Recursive Insertion Sort (original) (raw)

Last Updated : 7 Nov, 2025

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:

  1. If the array size n <= 1, it is already sorted (base case).
  2. Recursively call the function to sort the first n-1 elements.
  3. Store the last element (the nth element) in a temporary variable last.
  4. Shift all elements greater than last one position ahead.
  5. Insert last into its correct position.
  6. Repeat this process until the entire array is sorted. Python `

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: