1
1
/* *
2
+ *
2
3
* \file
3
- * \brief [Recursive Insertion Sort Algorithm
4
+ * \brief [Insertion Sort Algorithm
4
5
* (Insertion Sort)](https://en.wikipedia.org/wiki/Insertion_sort)
5
6
*
6
7
* \details
7
8
* Insertion sort is a simple sorting algorithm that builds the final
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.
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}
11
40
*/
12
41
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
42
+ #include < algorithm>
43
+ #include < cassert>
44
+ #include < iostream>
45
+ #include < vector>
17
46
18
47
/* * \namespace sorting
19
48
* \brief Sorting algorithms
20
49
*/
21
50
namespace sorting {
22
- /* *
23
- * \brief Recursive Insertion Sort Function for an array
51
+ /* * \brief
52
+ * Insertion Sort Function
24
53
*
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
54
+ * @tparam T type of array
55
+ * @param [in,out] arr Array to be sorted
56
+ * @param n Size of Array
28
57
*/
29
58
template <typename T>
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--;
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;
48
68
}
49
- arr[j + 1 ] = last;
50
69
}
51
70
52
- /* *
53
- * \brief Recursive Insertion Sort Function for a vector
71
+ /* * Insertion Sort Function
54
72
*
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
73
+ * @tparam T type of array
74
+ * @param [in,out] arr pointer to array to be sorted
58
75
*/
59
76
template <typename T>
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--;
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;
76
88
}
77
- arr->at (j + 1 ) = last;
78
89
}
79
90
80
91
} // namespace sorting
81
92
82
- /* *
83
- * \ brief Helper function to create a random array
93
+ /* *
94
+ * @ brief Create a random array objecthelper function to create a random array
84
95
*
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
96
+ * @tparam T type of array
97
+ * @param arr array to fill (must be pre-allocated)
98
+ * @param N number of array elements
88
99
*/
89
100
template <typename T>
90
101
static void create_random_array (T *arr, int N) {
@@ -94,57 +105,75 @@ static void create_random_array(T *arr, int N) {
94
105
}
95
106
}
96
107
97
- /* *
98
- * \brief Test cases to validate the recursive insertion sort algorithm
99
- */
108
+ /* * Test Cases to test algorithm */
100
109
void tests () {
101
110
int arr1[10 ] = {78 , 34 , 35 , 6 , 34 , 56 , 3 , 56 , 2 , 4 };
102
111
std::cout << " Test 1... " ;
103
- sorting::recursiveInsertionSort (arr1, 10 );
112
+ sorting::insertionSort (arr1, 10 );
104
113
assert (std::is_sorted (arr1, arr1 + 10 ));
105
114
std::cout << " passed" << std::endl;
106
115
107
116
int arr2[5 ] = {5 , -3 , 7 , -2 , 1 };
108
117
std::cout << " Test 2... " ;
109
- sorting::recursiveInsertionSort (arr2, 5 );
118
+ sorting::insertionSort (arr2, 5 );
110
119
assert (std::is_sorted (arr2, arr2 + 5 ));
111
120
std::cout << " passed" << std::endl;
112
121
113
122
float arr3[5 ] = {5.6 , -3.1 , -3.0 , -2.1 , 1.8 };
114
123
std::cout << " Test 3... " ;
115
- sorting::recursiveInsertionSort (arr3, 5 );
124
+ sorting::insertionSort (arr3, 5 );
116
125
assert (std::is_sorted (arr3, arr3 + 5 ));
117
126
std::cout << " passed" << std::endl;
118
127
119
128
std::vector<float > arr4 ({5.6 , -3.1 , -3.0 , -2.1 , 1.8 });
120
129
std::cout << " Test 4... " ;
121
- sorting::recursiveInsertionSort (&arr4, arr4. size () );
130
+ sorting::insertionSort (&arr4);
122
131
assert (std::is_sorted (std::begin (arr4), std::end (arr4)));
123
132
std::cout << " passed" << std::endl;
124
133
125
134
int arr5[50 ];
126
135
std::cout << " Test 5... " ;
127
136
create_random_array (arr5, 50 );
128
- sorting::recursiveInsertionSort (arr5, 50 );
137
+ sorting::insertionSort (arr5, 50 );
129
138
assert (std::is_sorted (arr5, arr5 + 50 ));
130
139
std::cout << " passed" << std::endl;
131
140
132
141
float arr6[50 ];
133
142
std::cout << " Test 6... " ;
134
143
create_random_array (arr6, 50 );
135
- sorting::recursiveInsertionSort (arr6, 50 );
144
+ sorting::insertionSort (arr6, 50 );
136
145
assert (std::is_sorted (arr6, arr6 + 50 ));
137
146
std::cout << " passed" << std::endl;
138
147
}
139
148
140
- /* *
141
- * \brief Main function
142
- *
143
- * Empty except for the call to `tests()`.
144
- *
145
- * @return 0 Always returns 0.
146
- */
149
+ /* * Main Function */
147
150
int main () {
151
+ // / Running predefined tests to test algorithm
148
152
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;
149
178
return 0 ;
150
179
}
0 commit comments