[cpp][11_sorts] bubble_down_sort, done.

This commit is contained in:
Liam Huang 2018-10-17 10:30:07 +08:00
parent 2dfdfe8a89
commit 1fe5a08dc9
2 changed files with 21 additions and 2 deletions

View File

@ -59,4 +59,16 @@ void selection_sort(BidirIt first,
} }
} }
template <typename BidirIt,
typename BinaryPred = std::less<typename std::iterator_traits<BidirIt>::value_type>>
void bubble_down_sort(BidirIt first, BidirIt last, BinaryPred comp = BinaryPred()) {
if (std::distance(first, last) <= 1) { return; }
for (auto it = first; it != last; ++it) {
for (auto itt = it + 1; itt != last; ++itt) {
if (comp(*itt, *it)) {
std::swap(*it, *itt);
}
}
}
}
#endif // SORTS_SORTS_HPP_ #endif // SORTS_SORTS_HPP_

View File

@ -14,18 +14,25 @@ int main() {
std::cout << '\n'; std::cout << '\n';
std::vector<int> b(test_data.begin(), test_data.end()); std::vector<int> b(test_data.begin(), test_data.end());
bubble_sort(b.begin(), b.end()); insertion_sort(b.begin(), b.end());
for (auto i : b) { for (auto i : b) {
std::cout << i << ' '; std::cout << i << ' ';
} }
std::cout << '\n'; std::cout << '\n';
std::vector<int> c(test_data.begin(), test_data.end()); std::vector<int> c(test_data.begin(), test_data.end());
bubble_sort(c.begin(), c.end()); selection_sort(c.begin(), c.end());
for (auto i : c) { for (auto i : c) {
std::cout << i << ' '; std::cout << i << ' ';
} }
std::cout << '\n'; std::cout << '\n';
std::vector<int> d(test_data.begin(), test_data.end());
bubble_down_sort(d.begin(), d.end());
for (auto i : d) {
std::cout << i << ' ';
}
std::cout << '\n';
return 0; return 0;
} }