Sorting algorithms/Counting sort: Difference between revisions

Content added Content deleted
(Added Haskell.)
(→‎{{header|Haskell}}: removed need for scoped type variables)
Line 220: Line 220:
We use lists for input and output rather than arrays, since lists are used more often in Haskell.
We use lists for input and output rather than arrays, since lists are used more often in Haskell.


<lang haskell>{-# LANGUAGE ScopedTypeVariables #-}
<lang haskell>import Control.Monad.ST

import Control.Monad.ST
import Data.Array.ST
import Data.Array.ST


countingSort :: forall n. (Enum n, Ix n) => [n] -> n -> n -> [n]
countingSort :: (Enum n, Ix n) => [n] -> n -> n -> [n]
countingSort l lo hi = concat $ zipWith replicate count [lo..]
countingSort l lo hi = concat $ zipWith replicate count [lo..]
where count = runST $ do
where count = runST $ do
a <- newArray (lo, hi) 0 :: ST s (STArray s n Int)
a <- myNewArray (lo, hi) 0
let increment i = readArray a i >>= writeArray a i . (+1)
let increment i = readArray a i >>= writeArray a i . (+1)
mapM_ increment l
mapM_ increment l
getElems a</lang>
getElems a
myNewArray :: (Ix n) => (n,n) -> Int -> ST s (STArray s n Int)
myNewArray = newArray</lang>


=={{header|Java}}==
=={{header|Java}}==