TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
recursive_bubble_sort.cpp
Go to the documentation of this file.
1
60#include <algorithm>
61#include <array>
62#include <cassert>
63#include <cstdint>
64#include <iostream>
65#include <vector>
66
71namespace sorting {
72
83template <typename T>
84void recursive_bubble_sort(std::vector<T> *nums, uint64_t n) {
85 if (n == 1) {
86 return;
87 }
88
89 for (uint64_t i = 0; i < n - 1; i++) {
91 if ((*nums)[i] > (*nums)[i + 1]) {
92 std::swap((*nums)[i], (*nums)[i + 1]);
93 }
94 }
95
97 recursive_bubble_sort(nums, n - 1);
98}
99} // namespace sorting
100
105static void test() {
106 // 1st example. Creating an array of type `int`.
107 std::cout << "1st test using `int`\n";
108 const uint64_t size = 6;
109 std::vector<int64_t> arr;
110 // populating the array
111 arr.push_back(22);
112 arr.push_back(46);
113 arr.push_back(94);
114 arr.push_back(12);
115 arr.push_back(37);
116 arr.push_back(63);
117 // array populating ends
118
120 assert(std::is_sorted(std::begin(arr), std::end(arr)));
121 std::cout << " 1st test passed!\n";
122 // printing the array
123 for (uint64_t i = 0; i < size; i++) {
124 std::cout << arr[i] << ", ";
125 }
126 std::cout << std::endl;
127
128 // 2nd example. Creating an array of type `double`.
129 std::cout << "2nd test using doubles\n";
130 std::vector<double> double_arr;
131
132 // populating the array
133 double_arr.push_back(20.4);
134 double_arr.push_back(62.7);
135 double_arr.push_back(12.2);
136 double_arr.push_back(43.6);
137 double_arr.push_back(74.1);
138 double_arr.push_back(57.9);
139 // array populating ends
140
141 sorting::recursive_bubble_sort(&double_arr, size);
142 assert(std::is_sorted(std::begin(double_arr), std::end(double_arr)));
143 std::cout << " 2nd test passed!\n";
144 // printing the array
145 for (uint64_t i = 0; i < size; i++) {
146 std::cout << double_arr[i] << ", ";
147 }
148 std::cout << std::endl;
149}
150
155int main() {
156 test(); // run self-test implementations
157 return 0;
158}
for working with vectors
void recursive_bubble_sort(std::vector< T > *nums, uint64_t n)
This is an implementation of the recursive_bubble_sort. A vector is passed to the function which is t...
static void test()
Self-test implementations.
int main()
Main function.