TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
gnome_sort.cpp
Go to the documentation of this file.
1
18#include <algorithm> // for std::swap
19#include <array> // for std::array
20#include <cassert> // for assertions
21#include <iostream> // for io operations
22
27namespace sorting {
33template <typename T>
34void gnomeSort(T *arr, int size) {
35 // few easy cases
36 if (size <= 1) {
37 return;
38 }
39
40 int index = 0; // initialize some variables.
41 while (index < size) {
42 // check for swap
43 if ((index == 0) || (arr[index] >= arr[index - 1])) {
44 index++;
45 } else {
46 std::swap(arr[index], arr[index - 1]); // swap
47 index--;
48 }
49 }
50}
51
61template <typename T, size_t size>
62std::array<T, size> gnomeSort(std::array<T, size> arr) {
63 // few easy cases
64 if (size <= 1) {
65 return arr;
66 }
67
68 int index = 0; // initialize loop index
69 while (index < size) {
70 // check for swap
71 if ((index == 0) || (arr[index] >= arr[index - 1])) {
72 index++;
73 } else {
74 std::swap(arr[index], arr[index - 1]); // swap
75 index--;
76 }
77 }
78 return arr;
79}
80} // namespace sorting
81
85static void test() {
86 // Example 1. Creating array of int,
87 std::cout << "Test 1 - as a C-array...";
88 const int size = 6;
89 std::array<int, size> arr = {-22, 100, 150, 35, -10, 99};
90 sorting::gnomeSort(arr.data(),
91 size); // pass array data as a C-style array pointer
92 assert(std::is_sorted(std::begin(arr), std::end(arr)));
93 std::cout << " Passed\n";
94 for (int i = 0; i < size; i++) {
95 std::cout << arr[i] << ", ";
96 }
97 std::cout << std::endl;
98
99 // Example 2. Creating array of doubles.
100 std::cout << "\nTest 2 - as a std::array...";
101 std::array<double, size> double_arr = {-100.2, 10.2, 20.0, 9.0, 7.5, 7.2};
102 std::array<double, size> sorted_arr = sorting::gnomeSort(double_arr);
103 assert(std::is_sorted(std::begin(sorted_arr), std::end(sorted_arr)));
104 std::cout << " Passed\n";
105 for (int i = 0; i < size; i++) {
106 std::cout << double_arr[i] << ", ";
107 }
108 std::cout << std::endl;
109
110 // Example 3. Creating random array of float.
111 std::cout << "\nTest 3 - 200 random numbers as a std::array...";
112 const int size2 = 200;
113 std::array<float, size2> rand_arr{};
114
115 for (auto &a : rand_arr) {
116 // generate random numbers between -5.0 and 4.99
117 a = float(std::rand() % 1000 - 500) / 100.f;
118 }
119
120 std::array<float, size2> float_arr = sorting::gnomeSort(rand_arr);
121 assert(std::is_sorted(std::begin(float_arr), std::end(float_arr)));
122 std::cout << " Passed\n";
123 // for (int i = 0; i < size; i++) std::cout << double_arr[i] << ", ";
124 std::cout << std::endl;
125}
126
130int main() {
131 test();
132 return 0;
133}
static void test()
int main()
for working with vectors
void gnomeSort(T *arr, int size)