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
59
60#include <algorithm>
61#include <cassert>
62#include <cstdint>
63#include <iostream>
64#include <vector>
65
70namespace sorting {
71
82template <typename T>
83void recursive_bubble_sort(std::vector<T> *nums, uint64_t n) {
84 if (n == 1) {
85 return;
86 }
87
88 for (uint64_t i = 0; i < n - 1; i++) {
90 if ((*nums)[i] > (*nums)[i + 1]) {
91 std::swap((*nums)[i], (*nums)[i + 1]);
92 }
93 }
94
96 recursive_bubble_sort(nums, n - 1);
97}
98} // namespace sorting
99
104static void test() {
105 // 1st example. Creating an array of type `int`.
106 std::cout << "1st test using `int`\n";
107 const uint64_t size = 6;
108 std::vector<int64_t> arr;
109 // populating the array
110 arr.push_back(22);
111 arr.push_back(46);
112 arr.push_back(94);
113 arr.push_back(12);
114 arr.push_back(37);
115 arr.push_back(63);
116 // array populating ends
117
119 assert(std::is_sorted(std::begin(arr), std::end(arr)));
120 std::cout << " 1st test passed!\n";
121 // printing the array
122 for (uint64_t i = 0; i < size; i++) {
123 std::cout << arr[i] << ", ";
124 }
125 std::cout << std::endl;
126
127 // 2nd example. Creating an array of type `double`.
128 std::cout << "2nd test using doubles\n";
129 std::vector<double> double_arr;
130
131 // populating the array
132 double_arr.push_back(20.4);
133 double_arr.push_back(62.7);
134 double_arr.push_back(12.2);
135 double_arr.push_back(43.6);
136 double_arr.push_back(74.1);
137 double_arr.push_back(57.9);
138 // array populating ends
139
140 sorting::recursive_bubble_sort(&double_arr, size);
141 assert(std::is_sorted(std::begin(double_arr), std::end(double_arr)));
142 std::cout << " 2nd test passed!\n";
143 // printing the array
144 for (uint64_t i = 0; i < size; i++) {
145 std::cout << double_arr[i] << ", ";
146 }
147 std::cout << std::endl;
148}
149
154int main() {
155 test(); // run self-test implementations
156 return 0;
157}
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.