|
| 1 | +#include <bits/stdc++.h> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +// A recursive function to implement Strand |
| 5 | +// sort. |
| 6 | +// ip is input list of items (unsorted). |
| 7 | +// op is output list of items (sorted) |
| 8 | +void strandSort(list<int> &ip, list<int> &op) |
| 9 | +{ |
| 10 | + // Base case : input is empty |
| 11 | + if (ip.empty()) |
| 12 | + return; |
| 13 | + |
| 14 | + // Create a sorted sublist with |
| 15 | + // first item of input list as |
| 16 | + // first item of the sublist |
| 17 | + list<int> sublist; |
| 18 | + sublist.push_back(ip.front()); |
| 19 | + ip.pop_front(); |
| 20 | + |
| 21 | + // Traverse remaining items of ip list |
| 22 | + for (auto it = ip.begin(); it != ip.end(); ) { |
| 23 | + |
| 24 | + // If current item of input list |
| 25 | + // is greater than last added item |
| 26 | + // to sublist, move current item |
| 27 | + // to sublist as sorted order is |
| 28 | + // maintained. |
| 29 | + if (*it > sublist.back()) { |
| 30 | + sublist.push_back(*it); |
| 31 | + |
| 32 | + // erase() on list removes an |
| 33 | + // item and returns iterator to |
| 34 | + // next of removed item. |
| 35 | + it = ip.erase(it); |
| 36 | + } |
| 37 | + |
| 38 | + // Otherwise ignore current element |
| 39 | + else |
| 40 | + it++; |
| 41 | + } |
| 42 | + |
| 43 | + // Merge current sublist into output |
| 44 | + op.merge(sublist); |
| 45 | + |
| 46 | + // Recur for remaining items in |
| 47 | + // input and current items in op. |
| 48 | + strandSort(ip, op); |
| 49 | +} |
| 50 | + |
| 51 | +// Driver code |
| 52 | +int main(void) |
| 53 | +{ |
| 54 | + list<int> ip{10, 5, 30, 40, 2, 4, 9}; |
| 55 | + |
| 56 | + // To store sorted output list |
| 57 | + list<int> op; |
| 58 | + |
| 59 | + // Sorting the list |
| 60 | + strandSort(ip, op); |
| 61 | + |
| 62 | + // Printing the sorted list |
| 63 | + for (auto x : op) |
| 64 | + cout << x << " "; |
| 65 | + return 0; |
| 66 | +} |
0 commit comments