1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Run{ int first, last, pos; };
template<typename T> ostream & operator << ( ostream &out, const vector<T> &V )
{
for ( T e : V ) out << e << " ";
return out;
}
int main()
{
vector<int> A = {1,2,4,3,5,6,8,7,9,11,10,12,13};
cout << "Original array:\n" << A << "\n\n";
// Find sorted runs
vector<Run> runs;
Run R{ 0, 0, 0 };
for ( int i = 1; i < A.size(); i++ )
{
if ( A[i] < A[i-1] ) // wind up current run and start a new one
{
R.last = i - 1;
runs.push_back( R );
R = Run{ i, i, i };
}
}
R.last = A.size() - 1;
runs.push_back( R );
cout << "Runs are (first:last):\n";
for ( auto r : runs ) cout << r.first << " : " << r.last << '\n';
// Merge sorted runs
vector<int> B;
while ( !runs.empty() )
{
auto it = min_element( runs.begin(), runs.end(), [&A]( Run a, Run b ){ return A[a.pos] < A[b.pos]; } );
B.push_back( A[it->pos] );
it->pos++;
if ( it->pos > it->last ) runs.erase( it );
}
cout << "\nSorted array:\n" << B << "\n\n";
}
|