TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
bubble_sort.cpp
Go to the documentation of this file.
1
49#include <algorithm>
50#include <cassert>
51#include <iostream>
52#include <string>
53#include <utility>
54#include <vector>
55
60namespace sorting {
65namespace bubble_sort {
71template <typename T>
72std::vector<T> bubble_sort(std::vector<T>& array) {
73 // swap_check flag to terminate the function early
74 // if there is no swap occurs in one iteration.
75 bool swap_check = true;
76 int size = array.size();
77 for (int i = 0; (i < size) && (swap_check); i++) {
78 swap_check = false;
79 for (int j = 0; j < size - 1 - i; j++) {
80 if (array[j] > array[j + 1]) {
81 swap_check = true;
82 std::swap(array[j], array[j + 1]);
83 }
84 }
85 }
86
87 return array;
88}
89} // namespace bubble_sort
90} // namespace sorting
91
96static void test() {
97 std::vector<int> vec_1 = {3, 1, -9, 0};
98 std::vector<int> sorted_1 = sorting::bubble_sort::bubble_sort(vec_1);
99
100 std::vector<int> vec_2 = {3};
101 std::vector<int> sorted_2 = sorting::bubble_sort::bubble_sort(vec_2);
102
103 std::vector<int> vec_3 = {10, 10, 10, 10, 10};
104 std::vector<int> sorted_3 = sorting::bubble_sort::bubble_sort(vec_3);
105
106 std::vector<float> vec_4 = {1234, -273.1, 23, 150, 1234, 1555.55, -2000};
107 std::vector<float> sorted_4 = sorting::bubble_sort::bubble_sort(vec_4);
108
109 std::vector<char> vec_5 = {'z', 'Z', 'a', 'B', ' ', 'c', 'a'};
110 std::vector<char> sorted_5 = sorting::bubble_sort::bubble_sort(vec_5);
111
112 std::vector<std::string> vec_6 = {"Hello", "hello", "Helo", "Hi", "hehe"};
113 std::vector<std::string> sorted_6 = sorting::bubble_sort::bubble_sort(vec_6);
114
115 std::vector<std::pair<int, char>> vec_7 = {{10, 'c'}, {2, 'z'}, {10, 'a'}, {0, 'b'}, {-1, 'z'}};
116 std::vector<std::pair<int, char>> sorted_7 = sorting::bubble_sort::bubble_sort(vec_7);
117
118 assert(std::is_sorted(sorted_1.begin(), sorted_1.end()));
119 assert(std::is_sorted(sorted_2.begin(), sorted_2.end()));
120 assert(std::is_sorted(sorted_3.begin(), sorted_3.end()));
121 assert(std::is_sorted(sorted_4.begin(), sorted_4.end()));
122 assert(std::is_sorted(sorted_5.begin(), sorted_5.end()));
123 assert(std::is_sorted(sorted_6.begin(), sorted_6.end()));
124 assert(std::is_sorted(sorted_7.begin(), sorted_7.end()));
125}
126
131int main() {
132 test();
133 return 0;
134}
static void test()
Self-test implementation.
int main()
Main function.
Bubble sort algorithm.
for working with vectors