Sorting algorithms/Sleep sort: Difference between revisions

Content added Content deleted
(→‎{{header|Haskell}}: tabs->spaces; type sig; discussion)
Line 608: Line 608:
sleepSort :: [Int] -> IO ()
sleepSort :: [Int] -> IO ()
sleepSort values = do
sleepSort values = do
chan <- newChan
chan <- newChan
forM_ values (\time -> forkIO (threadDelay (50000 * time) >> writeChan chan time))
forM_ values (\time -> forkIO (threadDelay (50000 * time) >> writeChan chan time))
forM_ values (const (readChan chan >>= print))
forM_ values (\_ -> readChan chan >>= print)


main :: IO ()
main :: IO ()
Line 620: Line 620:
import Control.Concurrent.Async
import Control.Concurrent.Async


sleepSort :: [Int] -> IO [()]
sleepSort :: [Int] -> IO ()
sleepSort = mapConcurrently (\x -> threadDelay (x*10^4) >> print x)
sleepSort = (() <$) . mapConcurrently (\x -> threadDelay (x*10^4) >> print x)


main :: IO [()]
main :: IO ()
main = getArgs >>= sleepSort . map read</lang>
main = getArgs >>= sleepSort . map read</lang>

This is problematic for inputs with multiple duplicates like <code>[1,2,3,1,4,1,5,1]</code> because simultaneous <code>print</code>s are done concurrently and the 1s and newlines get output in jumbled up order. The channels-based version above doesn't have this problem.


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==