File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ // This is the most simple implementation of sleeping sort in c++//
2+ #include < iostream>
3+ #include < thread>
4+ #include < vector>
5+ #include < chrono>
6+ using namespace std ;
7+
8+ void sleepSort (int *, int );
9+ void sleep (int );
10+
11+ int main ()
12+ {
13+ // initialize an array of integers to be sorted
14+ // Doesn't work for negative numbers
15+ int arr[] = { 3 ,2 ,1 };
16+ int n = sizeof (arr) / sizeof (arr[0 ]);
17+
18+ // find the max element in arr
19+ // Why to ding max? Read below
20+ int max = arr[0 ];
21+ for (int i = 0 ; i < n; i++) {
22+ if (arr[i] > max) max = arr[i];
23+ }
24+ max++;
25+
26+ // call the function SLEEPSORT()
27+ sleepSort (arr, n);
28+
29+ // make the main thread to go to sleep for 1 second more then
30+ // the largest number in the list.
31+ // this ensures all the threads are over before main finishes execution.
32+ std::this_thread::sleep_for (std::chrono::seconds (max));
33+
34+
35+ return (0 );
36+ }
37+
38+ void sleep ( int i) {
39+ // make the thread to sleep for I seconds.
40+ std::this_thread::sleep_for (std::chrono::seconds (i));
41+ cout << i << " " ;
42+ }
43+
44+ void sleepSort (int * arr, int n) {
45+ thread* threads;
46+ threads = new thread[n];
47+ for (int i = 0 ; i < n; i++) {
48+ // a new thread is created for each element of an array, which goes to sleep for arr[i] seconds.
49+ threads[i] = (thread (sleep, arr[i]));
50+ }
51+ }
You can’t perform that action at this time.
0 commit comments