Java Program for Recursive Insertion Sort
Last Updated :
14 Mar, 2023
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
import java.util.Arrays;
public class GFG
{
static void insertionSortRecursive( int arr[], int n)
{
if (n <= 1 )
return ;
insertionSortRecursive( arr, n- 1 );
int last = arr[n- 1 ];
int j = n- 2 ;
while (j >= 0 && arr[j] > last)
{
arr[j+ 1 ] = arr[j];
j--;
}
arr[j+ 1 ] = last;
}
public static void main(String[] args)
{
int arr[] = { 12 , 11 , 13 , 5 , 6 };
insertionSortRecursive(arr, arr.length);
System.out.println(Arrays.toString(arr));
}
}
|
Javascript
function insertionSortRecursive(arr, n) {
if (n <= 1) {
return ;
}
insertionSortRecursive(arr, n - 1);
const last = arr[n - 1];
let j = n - 2;
while (j >= 0 && arr[j] > last) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = last;
}
const arr = [12, 11, 13, 5, 6];
insertionSortRecursive(arr, arr.length);
console.log(arr);
|
Output:-
[5, 6, 11, 12, 13]
Time Complexity: O(n2)
Auxiliary Space: O(1)
Please refer complete article on Recursive Insertion Sort for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...