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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
- C Program for Recursive Insertion Sort
- Java Program for Recursive Insertion Sort
- Python Program for Recursive Insertion Sort
- Insertion sort to sort even and odd positioned elements in different orders
- Merge Sort vs. Insertion Sort
- Recursive insertion and traversal linked list
- Time complexity of insertion sort when there are O(n) inversions?
- An Insertion Sort time complexity question
- Insertion Sort
- Insertion Sort for Doubly Linked List
- C Program for Insertion Sort
- Insertion sort using C++ STL
- C Program for Binary Insertion Sort
- Java Program for Binary Insertion Sort
- Python Program for Binary Insertion Sort
- Insertion Sort by Swapping Elements
- C program for Time Complexity plot of Bubble, Insertion and Selection Sort using Gnuplot
- Sorting algorithm visualization : Insertion Sort
- Binary Insertion Sort