1
1
/* *
2
- *
3
2
* \file
4
- * \brief [Insertion Sort Algorithm
3
+ * \brief [Recursive Insertion Sort Algorithm
5
4
* (Insertion Sort)](https://en.wikipedia.org/wiki/Insertion_sort)
6
5
*
7
6
* \details
8
7
* Insertion sort is a simple sorting algorithm that builds the final
9
- * sorted array one at a time. It is much less efficient compared to
10
- * other sorting algorithms like heap sort, merge sort or quick sort.
11
- * However it has several advantages such as
12
- * 1. Easy to implement
13
- * 2. For small set of data it is quite efficient
14
- * 3. More efficient that other Quadratic complexity algorithms like
15
- * Selection sort or bubble sort.
16
- * 4. It's stable that is it does not change the relative order of
17
- * elements with equal keys
18
- * 5. Works on hand means it can sort the array or list as it receives.
19
- *
20
- * It is based on the same idea that people use to sort the playing cards in
21
- * their hands.
22
- * the algorithms goes in the manner that we start iterating over the array
23
- * of elements as soon as we find a unsorted element that is a misplaced
24
- * element we place it at a sorted position.
25
- *
26
- * Example execution steps:
27
- * 1. Suppose initially we have
28
- * \f{bmatrix}{4 &3 &2 &5 &1\f}
29
- * 2. We start traversing from 4 till we reach 1
30
- * when we reach at 3 we find that it is misplaced so we take 3 and place
31
- * it at a correct position thus the array will become
32
- * \f{bmatrix}{3 &4 &2 &5 &1\f}
33
- * 3. In the next iteration we are at 2 we find that this is also misplaced so
34
- * we place it at the correct sorted position thus the array in this iteration
35
- * becomes
36
- * \f{bmatrix}{2 &3 &4 &5 &1\f}
37
- * 4. We do not do anything with 5 and move on to the next iteration and
38
- * select 1 which is misplaced and place it at correct position. Thus, we have
39
- * \f{bmatrix}{1 &2 &3 &4 &5\f}
8
+ * sorted array one at a time. The recursive version applies the same
9
+ * logic but sorts the sub-array recursively before inserting the current
10
+ * element in its correct position.
40
11
*/
41
12
42
- #include < algorithm>
43
- #include < cassert>
44
- #include < iostream>
45
- #include < vector>
13
+ #include < algorithm> // for std::is_sorted and std::swap
14
+ #include < cassert> // for assert
15
+ #include < iostream> // for std::cout and std::endl
16
+ #include < vector> // for std::vector
46
17
47
18
/* * \namespace sorting
48
19
* \brief Sorting algorithms
49
20
*/
50
21
namespace sorting {
51
- /* * \brief
52
- * Insertion Sort Function
22
+ /* *
23
+ * \brief Recursive Insertion Sort Function for an array
53
24
*
54
- * @tparam T type of array
55
- * @param [in,out] arr Array to be sorted
56
- * @param n Size of Array
25
+ * @tparam T Type of the elements in the array
26
+ * @param[in,out] arr Pointer to the array to be sorted
27
+ * @param[in] n Size of the array
57
28
*/
58
29
template <typename T>
59
- void insertionSort (T *arr, int n) {
60
- for (int i = 1 ; i < n; i++) {
61
- T temp = arr[i];
62
- int j = i - 1 ;
63
- while (j >= 0 && temp < arr[j]) {
64
- arr[j + 1 ] = arr[j];
65
- j--;
66
- }
67
- arr[j + 1 ] = temp;
30
+ void recursiveInsertionSort (T *arr, int n) {
31
+ // Base case: Array of size 1 is already sorted
32
+ if (n <= 1 ) {
33
+ return ;
34
+ }
35
+
36
+ // Sort the first n-1 elements recursively
37
+ recursiveInsertionSort (arr, n - 1 );
38
+
39
+ // Insert the nth element at its correct position in the sorted array
40
+ T last = arr[n - 1 ];
41
+ int j = n - 2 ;
42
+
43
+ // Move elements of arr[0..n-1] that are greater than last to one
44
+ // position ahead of their current position
45
+ while (j >= 0 && arr[j] > last) {
46
+ arr[j + 1 ] = arr[j];
47
+ j--;
68
48
}
49
+ arr[j + 1 ] = last;
69
50
}
70
51
71
- /* * Insertion Sort Function
52
+ /* *
53
+ * \brief Recursive Insertion Sort Function for a vector
72
54
*
73
- * @tparam T type of array
74
- * @param [in,out] arr pointer to array to be sorted
55
+ * @tparam T Type of the elements in the vector
56
+ * @param[in,out] arr Pointer to the vector to be sorted
57
+ * @param[in] n Size of the vector
75
58
*/
76
59
template <typename T>
77
- void insertionSort (std::vector<T> *arr) {
78
- size_t n = arr->size ();
79
-
80
- for (size_t i = 1 ; i < n; i++) {
81
- T temp = arr[0 ][i];
82
- int32_t j = i - 1 ;
83
- while (j >= 0 && temp < arr[0 ][j]) {
84
- arr[0 ][j + 1 ] = arr[0 ][j];
85
- j--;
86
- }
87
- arr[0 ][j + 1 ] = temp;
60
+ void recursiveInsertionSort (std::vector<T> *arr, size_t n) {
61
+ // Base case: If the vector has one or fewer elements, it's already sorted
62
+ if (n <= 1 ) {
63
+ return ;
64
+ }
65
+
66
+ // Sort the first n-1 elements recursively
67
+ recursiveInsertionSort (arr, n - 1 );
68
+
69
+ // Insert the nth element at its correct position in the sorted vector
70
+ T last = arr->at (n - 1 );
71
+ int j = n - 2 ;
72
+
73
+ while (j >= 0 && arr->at (j) > last) {
74
+ arr->at (j + 1 ) = arr->at (j);
75
+ j--;
88
76
}
77
+ arr->at (j + 1 ) = last;
89
78
}
90
79
91
80
} // namespace sorting
92
81
93
- /* *
94
- * @ brief Create a random array objecthelper function to create a random array
82
+ /* *
83
+ * \ brief Helper function to create a random array
95
84
*
96
- * @tparam T type of array
97
- * @param arr array to fill (must be pre-allocated)
98
- * @param N number of array elements
85
+ * @tparam T Type of array elements
86
+ * @param[out] arr Pointer to the array to be filled
87
+ * @param[in] N Size of the array
99
88
*/
100
89
template <typename T>
101
90
static void create_random_array (T *arr, int N) {
@@ -105,75 +94,57 @@ static void create_random_array(T *arr, int N) {
105
94
}
106
95
}
107
96
108
- /* * Test Cases to test algorithm */
97
+ /* *
98
+ * \brief Test cases to validate the recursive insertion sort algorithm
99
+ */
109
100
void tests () {
110
101
int arr1[10 ] = {78 , 34 , 35 , 6 , 34 , 56 , 3 , 56 , 2 , 4 };
111
102
std::cout << " Test 1... " ;
112
- sorting::insertionSort (arr1, 10 );
103
+ sorting::recursiveInsertionSort (arr1, 10 );
113
104
assert (std::is_sorted (arr1, arr1 + 10 ));
114
105
std::cout << " passed" << std::endl;
115
106
116
107
int arr2[5 ] = {5 , -3 , 7 , -2 , 1 };
117
108
std::cout << " Test 2... " ;
118
- sorting::insertionSort (arr2, 5 );
109
+ sorting::recursiveInsertionSort (arr2, 5 );
119
110
assert (std::is_sorted (arr2, arr2 + 5 ));
120
111
std::cout << " passed" << std::endl;
121
112
122
113
float arr3[5 ] = {5.6 , -3.1 , -3.0 , -2.1 , 1.8 };
123
114
std::cout << " Test 3... " ;
124
- sorting::insertionSort (arr3, 5 );
115
+ sorting::recursiveInsertionSort (arr3, 5 );
125
116
assert (std::is_sorted (arr3, arr3 + 5 ));
126
117
std::cout << " passed" << std::endl;
127
118
128
119
std::vector<float > arr4 ({5.6 , -3.1 , -3.0 , -2.1 , 1.8 });
129
120
std::cout << " Test 4... " ;
130
- sorting::insertionSort (&arr4);
121
+ sorting::recursiveInsertionSort (&arr4, arr4. size () );
131
122
assert (std::is_sorted (std::begin (arr4), std::end (arr4)));
132
123
std::cout << " passed" << std::endl;
133
124
134
125
int arr5[50 ];
135
126
std::cout << " Test 5... " ;
136
127
create_random_array (arr5, 50 );
137
- sorting::insertionSort (arr5, 50 );
128
+ sorting::recursiveInsertionSort (arr5, 50 );
138
129
assert (std::is_sorted (arr5, arr5 + 50 ));
139
130
std::cout << " passed" << std::endl;
140
131
141
132
float arr6[50 ];
142
133
std::cout << " Test 6... " ;
143
134
create_random_array (arr6, 50 );
144
- sorting::insertionSort (arr6, 50 );
135
+ sorting::recursiveInsertionSort (arr6, 50 );
145
136
assert (std::is_sorted (arr6, arr6 + 50 ));
146
137
std::cout << " passed" << std::endl;
147
138
}
148
139
149
- /* * Main Function */
140
+ /* *
141
+ * \brief Main function
142
+ *
143
+ * Empty except for the call to `tests()`.
144
+ *
145
+ * @return 0 Always returns 0.
146
+ */
150
147
int main () {
151
- // / Running predefined tests to test algorithm
152
148
tests ();
153
-
154
- // / For user insteraction
155
- size_t n;
156
- std::cout << " Enter the length of your array (0 to exit): " ;
157
- std::cin >> n;
158
- if (n == 0 ) {
159
- return 0 ;
160
- }
161
-
162
- int *arr = new int [n];
163
- std::cout << " Enter any " << n << " Numbers for Unsorted Array : " ;
164
-
165
- for (int i = 0 ; i < n; i++) {
166
- std::cin >> arr[i];
167
- }
168
-
169
- sorting::insertionSort (arr, n);
170
-
171
- std::cout << " \n Sorted Array : " ;
172
- for (int i = 0 ; i < n; i++) {
173
- std::cout << arr[i] << " " ;
174
- }
175
-
176
- std::cout << std::endl;
177
- delete[] arr;
178
149
return 0 ;
179
150
}
0 commit comments