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
// 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]
Refer Insertion Sort for more details.
How to implement it recursively?
Recursive Insertion Sort has no performance/implementation advantages, but can be a good question to check one’s understanding of Insertion Sort and recursion.
If we take a closer look at Insertion Sort algorithm, we keep processed elements sorted and insert new elements one by one in the inserted array.
- Base Case: If array size is 1 or smaller, return.
- Recursively sort first n-1 elements.
- Insert last element at its correct position in sorted array.
Below is implementation of above idea.
5 6 11 12 13
This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.about the topic discussed above
- C Program for Recursive Insertion Sort
- Java Program for Recursive Insertion Sort
- Python Program for Recursive Insertion Sort
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
- Insertion sort to sort even and odd positioned elements in different orders
- Recursive insertion and traversal linked list
- Insertion Sort
- Insertion sort using C++ STL
- Binary Insertion Sort
- C Program for Insertion Sort
- C Program for Binary Insertion Sort
- Insertion Sort by Swapping Elements
- An Insertion Sort time complexity question
- Time complexity of insertion sort when there are O(n) inversions?
- Java Program for Binary Insertion Sort