Recursive Insertion Sort
Recursive Insertion Sort
Recursive Insertion Sort
AfterAcademy
Admin AfterAcademy
23 Sep 2020
Difficulty: Medium
Example 1
https://afteracademy.com/blog/recursive-insertion-sort/ 1/7
1/2/25, 12:15 PM Recursive Insertion Sort
Example 2
Solution
The problem expects us to sort an array using Insertion sort and we have to
do it recursively. You can read about insertion sort here.
Now, we know that Recursion is made for solving problems that can be
broken down into smaller, repetitive problems. In this case, we can define
our smaller problems in this way “we have a sorted array and now we have
to insert a number in that sorted array”.
Now, every recursive function requires a base case for its termination. In
this case, we can say that if the array is of size 1, then the array is already
https://afteracademy.com/blog/recursive-insertion-sort/ 2/7
1/2/25, 12:15 PM Recursive Insertion Sort
Now, the problem is to find a way to insert a value in a sorted array and that
can be done as shown in the above visualization. We will simply shift the
array elements to find the right position for the new element. As soon as we
place the new element in its correct position, our sorted array size will
increase by one.
Example:
Solution Steps
Insert the last element at its correct position in the sorted array.
https://afteracademy.com/blog/recursive-insertion-sort/ 3/7
1/2/25, 12:15 PM Recursive Insertion Sort
Pseudo Code
Complexity Analysis
Can you prove that our assumption about the array is sorted in each
recursion frame is correct for every case?
In the last line of pseudo-code, how did we make sure that pos+1 is
the correct position for the val to be inserted such that the
array[0..n] will stay sorted?
https://afteracademy.com/blog/recursive-insertion-sort/ 4/7
1/2/25, 12:15 PM Recursive Insertion Sort
Merge Sort
Please comment down below if you find an error/bug in the above explanation.
https://afteracademy.com/blog/recursive-insertion-sort/ 5/7
1/2/25, 12:15 PM Recursive Insertion Sort
https://afteracademy.com/blog/recursive-insertion-sort/ 6/7
1/2/25, 12:15 PM Recursive Insertion Sort
https://afteracademy.com/blog/recursive-insertion-sort/ 7/7