TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
insertion_sort_recursive.cpp
Go to the documentation of this file.
1
32#include <algorithm>
33#include <cassert>
34#include <iostream>
35#include <vector>
36
41namespace sorting {
42
50template <typename T>
51void insertionSort(T *arr, int n) {
52 for (int i = 1; i < n; i++) {
53 T temp = arr[i];
54 int j = i - 1;
55 while (j >= 0 && temp < arr[j]) {
56 arr[j + 1] = arr[j];
57 j--;
58 }
59 arr[j + 1] = temp;
60 }
61}
62
69template <typename T>
70void insertionSort(std::vector<T> *arr) {
71 size_t n = arr->size();
72
73 for (size_t i = 1; i < n; i++) {
74 T temp = arr->at(i);
75 int32_t j = i - 1;
76 while (j >= 0 && temp < arr->at(j)) {
77 arr->at(j + 1) = arr->at(j);
78 j--;
79 }
80 arr->at(j + 1) = temp;
81 }
82}
83
84} // namespace sorting
85
93template <typename T>
94static void create_random_array(T *arr, int N) {
95 while (N--) {
96 double r = (std::rand() % 10000 - 5000) / 100.f;
97 arr[N] = static_cast<T>(r);
98 }
99}
100
105static void tests() {
106 int arr1[10] = {78, 34, 35, 6, 34, 56, 3, 56, 2, 4};
107 std::cout << "Test 1... ";
108 sorting::insertionSort(arr1, 10);
109 assert(std::is_sorted(arr1, arr1 + 10));
110 std::cout << "passed" << std::endl;
111
112 int arr2[5] = {5, -3, 7, -2, 1};
113 std::cout << "Test 2... ";
114 sorting::insertionSort(arr2, 5);
115 assert(std::is_sorted(arr2, arr2 + 5));
116 std::cout << "passed" << std::endl;
117
118 float arr3[5] = {5.6, -3.1, -3.0, -2.1, 1.8};
119 std::cout << "Test 3... ";
120 sorting::insertionSort(arr3, 5);
121 assert(std::is_sorted(arr3, arr3 + 5));
122 std::cout << "passed" << std::endl;
123
124 std::vector<float> arr4({5.6, -3.1, -3.0, -2.1, 1.8});
125 std::cout << "Test 4... ";
127 assert(std::is_sorted(std::begin(arr4), std::end(arr4)));
128 std::cout << "passed" << std::endl;
129
130 int arr5[50];
131 std::cout << "Test 5... ";
132 create_random_array(arr5, 50);
133 sorting::insertionSort(arr5, 50);
134 assert(std::is_sorted(arr5, arr5 + 50));
135 std::cout << "passed" << std::endl;
136
137 float arr6[50];
138 std::cout << "Test 6... ";
139 create_random_array(arr6, 50);
140 sorting::insertionSort(arr6, 50);
141 assert(std::is_sorted(arr6, arr6 + 50));
142 std::cout << "passed" << std::endl;
143}
144
149int main() {
150 tests();
151 return 0;
152}
static void tests()
self test implementation
static void create_random_array(T *arr, int N)
Helper function to create a random array.
int main()
Main function.
for working with vectors
void insertionSort(T *arr, int n)
Insertion Sort Function.