How it works
Sort by timeouts.
Implementation
async function sleepSort(arr) { const result = []; const promises = arr.map(v => new Promise(r => setTimeout(() => { result.push(v); r(); }, v * 10)) ); await Promise.all(promises); return result; }
import asyncio async def sleep_sort(arr): result = [] async def delayed(v): await asyncio.sleep(v * 0.01) result.append(v) await asyncio.gather( *[delayed(v) for v in arr]) return result
void sleepSort(vector<int>& arr) { vector<int> result; mutex mtx; vector<thread> threads; for (int v : arr) threads.emplace_back([&, v]() { this_thread::sleep_for(chrono::milliseconds(v*10)); lock_guard<mutex> lock(mtx); result.push_back(v); }); for (auto& t : threads) t.join(); arr = result; }
async Task<int[]> SleepSort(int[] arr) { var result = new List<int>(); var tasks = arr.Select(v => Task.Run(async () => { await Task.Delay(v * 10); lock(result) result.Add(v); })).ToArray(); await Task.WhenAll(tasks); return result.ToArray(); }
// Sleep sort requires threading void* sleepThread(void* arg) { int v = *(int*)arg; usleep(v * 10000); printf("%d ", v); return NULL; } void sleepSort(int arr[], int n) { pthread_t threads[n]; for (int i = 0; i < n; i++) pthread_create(&threads[i], NULL, sleepThread, &arr[i]); for (int i = 0; i < n; i++) pthread_join(threads[i], NULL); }