1+ package com .thealgorithms .sorts ;
2+
3+ /**
4+ * Recursive Insertion Sort algorithm.
5+ *
6+ * This is a recursive implementation of the standard Insertion Sort algorithm.
7+ * Instead of iterating through the array, it sorts the first n-1 elements recursively
8+ * and then inserts the nth element into its correct position.
9+ *
10+ * Concept:
11+ * - Divide the problem into smaller subproblems by sorting first n-1 elements.
12+ * - Insert the last element into the sorted portion.
13+ *
14+ * Time Complexity:
15+ * - Best case: O(n) – array is already sorted
16+ * - Average case: O(n^2)
17+ * - Worst case: O(n^2) – array is reverse sorted
18+ *
19+ * Space Complexity:
20+ * - O(n) – due to recursion stack
21+ *
22+ * Note:
23+ * - This implementation is mainly useful for understanding recursion.
24+ * - Iterative insertion sort is preferred in production due to lower space overhead.
25+ *
26+ * @see SortAlgorithm
27+ */
28+ public class RecursiveInsertionSort implements SortAlgorithm {
29+
30+ /**
31+ * Sorts the given array using recursive insertion sort.
32+ *
33+ * @param array The array to be sorted
34+ * @param <T> The type of elements in the array, which must be comparable
35+ * @return The sorted array
36+ */
37+ @ Override
38+ public <T extends Comparable <T >> T [] sort (T [] array ) {
39+ if (array == null || array .length <= 1 ) {
40+ return array ;
41+ }
42+
43+ recursiveSort (array , array .length );
44+ return array ;
45+ }
46+
47+ /**
48+ * Recursively sorts the first n elements of the array.
49+ *
50+ * @param array The array to be sorted
51+ * @param n The number of elements to sort
52+ * @param <T> The type of elements in the array
53+ */
54+ private <T extends Comparable <T >> void recursiveSort (T [] array , int n ) {
55+
56+ // Base case: single element is already sorted
57+ if (n <= 1 ) {
58+ return ;
59+ }
60+
61+ // Recursively sort first n-1 elements
62+ recursiveSort (array , n - 1 );
63+
64+ // Insert the nth element into the sorted subarray
65+ insert (array , n );
66+ }
67+
68+ /**
69+ * Inserts the nth element into its correct position in the sorted subarray [0...n-2].
70+ *
71+ * @param array The array containing sorted subarray and one unsorted element
72+ * @param n The size of the subarray to consider
73+ * @param <T> The type of elements in the array
74+ */
75+ private <T extends Comparable <T >> void insert (T [] array , int n ) {
76+ final T key = array [n - 1 ];
77+ int j = n - 2 ;
78+
79+ // Shift elements greater than key to one position ahead
80+ while (j >= 0 && SortUtils .less (key , array [j ])) {
81+ array [j + 1 ] = array [j ];
82+ j --;
83+ }
84+
85+ // Place key at correct position
86+ array [j + 1 ] = key ;
87+ }
88+ }
0 commit comments