From 66555f90407dcd686776650fb20901ba03320026 Mon Sep 17 00:00:00 2001 From: Saket Kumar Date: Sat, 5 Oct 2019 10:38:10 +0530 Subject: [PATCH] Added strand sort --- strand_sort.cpp | 67 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 strand_sort.cpp diff --git a/strand_sort.cpp b/strand_sort.cpp new file mode 100644 index 0000000..22dc5d8 --- /dev/null +++ b/strand_sort.cpp @@ -0,0 +1,67 @@ +// CPP program to implement Strand Sort +#include +using namespace std; + +// A recursive function to implement Strand +// sort. +// ip is input list of items (unsorted). +// op is output list of items (sorted) +void strandSort(list &ip, list &op) +{ + // Base case : input is empty + if (ip.empty()) + return; + + // Create a sorted sublist with + // first item of input list as + // first item of the sublist + list sublist; + sublist.push_back(ip.front()); + ip.pop_front(); + + // Traverse remaining items of ip list + for (auto it = ip.begin(); it != ip.end(); ) { + + // If current item of input list + // is greater than last added item + // to sublist, move current item + // to sublist as sorted order is + // maintained. + if (*it > sublist.back()) { + sublist.push_back(*it); + + // erase() on list removes an + // item and returns iterator to + // next of removed item. + it = ip.erase(it); + } + + // Otherwise ignore current element + else + it++; + } + + // Merge current sublist into output + op.merge(sublist); + + // Recur for remaining items in + // input and current items in op. + strandSort(ip, op); +} + +// Driver code +int main(void) +{ + list ip{10, 5, 30, 40, 2, 4, 9}; + + // To store sorted output list + list op; + + // Sorting the list + strandSort(ip, op); + + // Printing the sorted list + for (auto x : op) + cout << x << " "; + return 0; +}