C++ Library Extensions 2022.12.09
To help learn modern C++ programming
017-quick_sort.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2
5
6// most optimized sequential quick sort algorithm
7template<typename ElementType>
8std::vector<ElementType> sequential_quick_sort( std::vector<ElementType> container)
9{
10 if(container.empty()) return container;
11
12 auto move_iterator = std::make_move_iterator<decltype(container.begin())>;
13 using container_t = std::vector<ElementType>;
14
15 container_t result{ container.back() };
16
17 // removing last element from the std::vector is very efficient
18 container.pop_back(); // removed last element
19
20
21 auto predicate = [pivot = result.front()](const auto& e)
22 {
23 return e < pivot;
24 };
25
26 auto itr = std::partition(container.begin(), container.end(), predicate);
27
28 auto sorted_lower_part = sequential_quick_sort(
29 container_t{ move_iterator(container.begin()), move_iterator(itr)});
30
31 auto sorted_higher_part = sequential_quick_sort(
32 container_t{ move_iterator(itr), move_iterator(container.end())});
33
34 result.insert(result.begin(),
35 move_iterator(sorted_lower_part.begin()),
36 move_iterator(sorted_lower_part.end()));
37
38 result.insert(result.end(),
39 move_iterator(sorted_higher_part.begin()),
40 move_iterator(sorted_higher_part.end()));
41
42 return result;
43}
44
46{
47 std::vector<int> container {5, 7, 3, 4, 1, 9, 2, 8, 10, 6};
48
49 stream << "Before Sort: " << container << endl;
50
51 stream << "After Sort: " << sequential_quick_sort(container) << endl;
52}
53
55{
56 std::vector<std::string> container {"banana", "dango", "cherry", "echo", "apple", "fox",
57 "hotel", "golf"};
58
59 stream << "Before Sort: " << container << endl;
60
61 stream << "After Sort: " << sequential_quick_sort(container) << endl;
62}
63
64int main()
65{
66 // test_sequential_quick_sort();
68}
tpf::sstream stream
void test_sequential_quick_sort_string()
void test_sequential_quick_sort()
auto endl
std::vector< ElementType > sequential_quick_sort(std::vector< ElementType > container)
int main()
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.