Sorting algorithms/Sleep sort: Difference between revisions

Content added Content deleted
m (→‎{{header|Scala}}: Did some formatting)
Line 114: Line 114:


=={{header|C++}}==
=={{header|C++}}==
{{works with|C++11}}
<lang cpp>
<lang cpp>
#include <chrono>
#include <iostream>
#include <iostream>
#include <thread>
#include <thread>
#include <vector>
#include <vector>
#include <unistd.h>


int main(int argc, char* argv[]) {
using namespace std;
std::vector<std::thread> threads;


for (int i = 1; i < argc; ++i) {
void sortThread( int x )
threads.emplace_back([i, &argv]() {
{
usleep( 10000 * x );
int arg = std::stoi(argv[i]);
std::this_thread::sleep_for(std::chrono::seconds(arg));
cout << x << " ";
std::cout << argv[i] << std::endl;
}
});
}


for (auto& thread : threads) {
int main()
thread.join();
{
}
vector<thread*> threads;

srand( ( unsigned )time( NULL ) );

cout << "unsorted:" << endl;
for( int x = 0; x < 15; x++ )
{
int r = rand() % 20 + 5;
cout << r << " ";
thread* t = new thread( sortThread, r );
threads.push_back( t );
}
cout << endl << endl << "sorted:" << endl;

for( vector<thread*>::iterator t = threads.begin(); t != threads.end(); t++ )
{
( *t )->join();
delete ( *t );
}

cout << endl << endl;
return 0;
}
}
</lang>
</lang>
{{out}}
{{out}}
<pre>
<pre>
./a.out 8 15 14 9 17 20 16 24 6 24 21 23 19 23 19
unsorted:
6
8 15 14 9 17 20 16 24 6 24 21 23 19 23 19
8

9
sorted:
14
6 8 9 14 15 16 17 19 19 20 21 23 23 24 24
15
16
17
19
19
20
21
23
23
24
24
</pre>
</pre>