Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program for Recursive Insertion Sort
In this article, we will learn about implementing insertion sort using recursion. Recursive insertion sort breaks down the sorting problem into smaller subproblems by recursively sorting the first n-1 elements and then inserting the last element in its correct position.
Problem statement ? We are given an array, we need to sort it using the concept of recursive insertion sort.
Insertion sort works by building a sorted portion of the array one element at a time. In the recursive approach, we sort the first n-1 elements recursively, then insert the nth element into its correct position.
Algorithm
The recursive insertion sort follows these steps ?
- Base case: If array size is 1 or less, it's already sorted
- Recursive call: Sort the first n-1 elements
- Insert: Place the last element in its correct position
Implementation
# Recursive insertion sort implementation
def insertionSortRecursive(arr, n):
# Base case: if array has 1 or 0 elements, it's already sorted
if n <= 1:
return
# Recursively sort first n-1 elements
insertionSortRecursive(arr, n-1)
# Insert the last element at its correct position
last = arr[n-1]
j = n-2
# Move elements greater than 'last' one position ahead
while (j >= 0 and arr[j] > last):
arr[j+1] = arr[j]
j = j-1
# Place 'last' at its correct position
arr[j+1] = last
# Main program
arr = [5, 3, 8, 1, 6, 2]
n = len(arr)
print("Original array:")
print(arr)
insertionSortRecursive(arr, n)
print("Sorted array:")
print(arr)
Original array: [5, 3, 8, 1, 6, 2] Sorted array: [1, 2, 3, 5, 6, 8]
How It Works
Let's trace through the execution with array [5, 3, 8, 1] ?
-
insertionSortRecursive([5, 3, 8, 1], 4)callsinsertionSortRecursive([5, 3, 8], 3) -
insertionSortRecursive([5, 3, 8], 3)callsinsertionSortRecursive([5, 3], 2) -
insertionSortRecursive([5, 3], 2)callsinsertionSortRecursive([5], 1) - Base case reached, returns
- Insert 3 in correct position:
[3, 5] - Insert 8 in correct position:
[3, 5, 8] - Insert 1 in correct position:
[1, 3, 5, 8]
Time Complexity
| Case | Time Complexity | Description |
|---|---|---|
| Best | O(n) | Array already sorted |
| Average | O(n²) | Random order |
| Worst | O(n²) | Reverse sorted array |
Space Complexity: O(n) due to recursion stack depth.
Conclusion
Recursive insertion sort provides an elegant way to understand the sorting algorithm through divide-and-conquer approach. While it has the same time complexity as iterative insertion sort, the recursive version uses additional space for the call stack.
