Open In App

Python Program for Recursive Insertion Sort

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. 

Python Program for Recursive Insertion Sort for Iterative algorithm for insertion sort

Algorithm

// 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]

Python




# Recursive Python program for insertion sort
 
# Recursive function to sort an array using insertion sort
def insertionSortRecursive(arr, n):
    # base case
    if n <= 1:
        return
 
    # Sort first n-1 elements
    insertionSortRecursive(arr, n - 1)
 
    # 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
    arr[j + 1] = last
 
 
# Driver program to test insertion sort
if __name__ == '__main__':
    A = [-7, 11, 6, 0, -3, 5, 10, 2]
    n = len(A)
    insertionSortRecursive(A, n)
    print(A)
 
# Contributed by Harsh Valecha,
# Edited by Abraar Masud Nafiz.


Output

[-7, -3, 0, 2, 5, 6, 10, 11]

Time Complexity: O(n2)

Auxiliary Space: O(n)

Python Program for Recursive Insertion Sort Using a divide and conquer

Step by step approach:

1.Define a function called insertion_sort_recursive that takes an array arr as input.
2.Check if the length of the input array is less than or equal to 1. If it is, return the array as it is already sorted.
3.Find the midpoint of the array by dividing its length by 2 using integer division.
4.Recursively sort the left half of the array by calling insertion_sort_recursive with the left half of the input array as its argument.
5.Recursively sort the right half of the array by calling insertion_sort_recursive with the right half of the input array as its argument.
6.Merge the sorted left and right halves of the array into a new sorted array.
7.Initialize two indices i and j to 0 to keep track of the current positions in the left and right halves of the array, respectively.
8.While i is less than the length of the left half and j is less than the length of the right half, compare the values at the current positions in the left and right halves of the array.
9.If the value at the current position in the left half is less than the value at the current position in the right half, append the value at the current position in the left half to the sorted array and increment i.
10.If the value at the current position in the right half is less than or equal to the value at the current position in the left half, append the value at the current position in the right half to the sorted array and increment j.
11.If either i or j has reached the end of its respective half of the array, append the remaining elements of the other half to the sorted array.
12.Return the sorted array

Python3




def insertion_sort_recursive(arr):
    # base case: return when array has only one element
    if len(arr) <= 1:
        return arr
 
    # recursively sort the first half of the array
    mid = len(arr) // 2
    left_half = insertion_sort_recursive(arr[:mid])
 
    # recursively sort the second half of the array
    right_half = insertion_sort_recursive(arr[mid:])
 
    # merge the sorted halves into a sorted array
    i, j = 0, 0
    sorted_arr = []
    while i < len(left_half) and j < len(right_half):
        if left_half[i] < right_half[j]:
            sorted_arr.append(left_half[i])
            i += 1
        else:
            sorted_arr.append(right_half[j])
            j += 1
    sorted_arr += left_half[i:]
    sorted_arr += right_half[j:]
 
    return sorted_arr
arr = [5, 2, 4, 6, 1, 3]
sorted_arr = insertion_sort_recursive(arr)
print(sorted_arr)  # Output: [1, 2, 3, 4, 5, 6]


Output

[1, 2, 3, 4, 5, 6]

Time complexity: O(n log n)
space complexity: O(n)



Previous Article
Next Article

Similar Reads

C++ Program for Recursive Insertion Sort
Insertion sort is a simple and efficient sorting algorithm that is often used for small lists or as a building block for more complex algorithms. It works by dividing the input list into two parts: a sorted sublist of items that has already been traversed, and an unsorted sublist of items remaining to be sorted. The algorithm begins with the second
3 min read
Java Program for Recursive Insertion Sort
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 Algorithm // 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] Java Code // Recursive Java program for inserti
2 min read
Recursive Insertion Sort
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 sortAlgorithm // 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] Example: Refer Insertion Sort for more details.H
6 min read
Comparison among Bubble Sort, Selection Sort and Insertion Sort
Bubble Sort, Selection Sort, and Insertion Sort are simple sorting algorithms that are commonly used to sort small datasets or as building blocks for more complex sorting algorithms. Here's a comparison of the three algorithms: Bubble Sort:Time complexity: O(n^2) in the worst and average cases, O(n) in the best case (when the input array is already
15 min read
Recursive insertion and traversal linked list
We have discussed different methods of linked list insertion. How to recursively create a linked list? Recursively inserting at the end: To create a Linked list using recursion follow these steps. Below steps insert a new node recursively at the end of linked list. C/C++ Code // Function to insert a new node at the // end of linked list using recur
9 min read
Insertion sort to sort even and odd positioned elements in different orders
We are given an array. We need to sort the even positioned elements in the ascending order and the odd positioned elements in the descending order. We must apply insertion sort to sort them.Examples: Input : a[] = {7, 10, 11, 3, 6, 9, 2, 13, 0} Output : 11 3 7 9 6 10 2 13 0 Even positioned elements after sorting int ascending order : 3 9 10 13 Odd
7 min read
Difference between Insertion sort and Selection sort
Insertion sort and selection sort are two popular sorting algorithms, and their main difference lies in how they select and place elements in a sorted sequence. Selection Sort:In selection sort, the input array is divided into two parts: a sorted part and an unsorted part.The algorithm repeatedly finds the minimum element in the unsorted part and s
14 min read
Sorting by combining Insertion Sort and Merge Sort algorithms
Insertion sort: The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.Advantages: Following are the advantages of insertion sort: If the size of the list to be sorted is small, insertion sort runs fasterInsertion sort takes O(N) time when eleme
2 min read
Count swaps required to sort an array using Insertion Sort
Given an array A[] of size N (1 ≤ N ≤ 105), the task is to calculate the number of swaps required to sort the array using insertion sort algorithm. Examples: Input: A[] = {2, 1, 3, 1, 2} Output: 4 Explanation: Step 1: arr[0] stays in its initial position. Step 2: arr[1] shifts 1 place to the left. Count = 1. Step 3: arr[2] stays in its initial posi
15 min read
Merge Sort vs. Insertion Sort
Pre-requisite: Merge Sort, Insertion Sort Merge Sort: is an external algorithm based on divide and conquer strategy. In this sorting:   The elements are split into two sub-arrays (n/2) again and again until only one element is left.Merge sort uses additional storage for sorting the auxiliary array.Merge sort uses three arrays where two are used for
14 min read
three90RightbarBannerImg