Sorting algorithms/Sleep sort

From Rosetta Code
Revision as of 13:24, 16 June 2011 by Sonia (talk | contribs) (New draft task: Sleep sort)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Sorting algorithms/Sleep sort is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.

Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.

Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.

Go

<lang go>import (

   "log"
   "os"
   "strconv"
   "sync"
   "time"

)

func main() {

   lg := log.New(os.Stdout, "", 0)
   var wg sync.WaitGroup
   wg.Add(len(os.Args) - 1)
   for _, a := range os.Args[1:] {
       if i, err := strconv.Atoi64(a); err == nil {
           time.AfterFunc(i*1e9, func() {
               lg.Print(i)
               wg.Done()
           })
       }
   }
   wg.Wait()

}</lang> Usage and output:

./sleepsort 3 1 4 1 5 9
1
1
3
4
5
9

UNIX Shell

Works with: Bash

<lang bash>#!/bin/bash function f() {

   sleep "$1"
   echo "$1"

} while [ -n "$1" ] do

   f "$1" &
   shift

done wait</lang> Usage and output:

./sleepsort 3 1 4 1 5 9
1
1
3
4
5
9