Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added strand sort #11

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions strand_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// CPP program to implement Strand Sort
#include <bits/stdc++.h>
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<int> &ip, list<int> &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<int> 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<int> ip{10, 5, 30, 40, 2, 4, 9};

// To store sorted output list
list<int> op;

// Sorting the list
strandSort(ip, op);

// Printing the sorted list
for (auto x : op)
cout << x << " ";
return 0;
}