TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
strand_sort.cpp
Go to the documentation of this file.
1
16#include <iostream>
17#include <list>
18
23namespace sorting {
28 namespace strand {
35 template <typename T>
36 std::list<T> strand_sort(std::list<T> lst) {
37 if (lst.size() < 2) { // Returns list if empty or contains only one element
38 return lst; // Returns list
39 }
40 std::list<T> result; // Define new "result" named list instance.
41 std::list<T> sorted; // Define new "sorted" named list instance.
42 while(!lst.empty()) /* if lst is not empty */ {
43 sorted.push_back(lst.front()); // Adds the first element of "lst" list to the bottom of the "sorted" list.
44 lst.pop_front(); // Remove first element of "lst" list.
45 for (auto it = lst.begin(); it != lst.end(); ) { // Return the loop as long as the current iterator is not equal to the last literator of the "lst" list.
46 if (sorted.back() <= *it) { // If the last reference of the "sorted" list is less than or equal to the current iterator reference.
47 sorted.push_back(*it); // Adds the iterator retrieved in the loop under the "sorted" list.
48 it = lst.erase(it); // Deletes the element with the current iterator and assigns the deleted element to the iterator.
49 } else {
50 it++; // Next iterator.
51 }
52 }
53 result.merge(sorted); // Merge "result" list with "sorted" list.
54 }
55 return result; // Returns sorted list
56 }
57 } // namespace strand
58} // namespace sorting
59
64static void test() {
65 std::list<int> lst = { -333, 525, 1, 0, 94, 52, 33 };
66
67 std::cout << "Before: ";
68 for(auto item: lst) {
69 std::cout << item << " ";
70 }
71
72 lst = sorting::strand::strand_sort(lst); // Sort list.
73
74 std::cout << "\nAfter: ";
75 for(auto item: lst) {
76 std::cout << item << " ";
77 }
78}
79
84int main() {
85 test();
86 return 0;
87}
for working with vectors
Functions for Strand Sort algorithm.
std::list< T > strand_sort(std::list< T > lst)
Apply sorting.
static void test()
Function for testing.
int main()
Main function.