Sorting Algorithms/Circle Sort: Difference between revisions

→‎{{header|Haskell}}: Changed Haskell implementation, removed monadic stuff, and cleaned
(→‎{{header|Haskell}}: Updated Haskell code)
(→‎{{header|Haskell}}: Changed Haskell implementation, removed monadic stuff, and cleaned)
Line 983:
 
This code uses the tortoise-and-the-hare technique to split the input list in two and compare the relevant positions.
It also uses the Writer monad to track whether or not there have been swaps.
 
<lang haskell>import Data.MonoidBool (Any(..)bool)
import Data.Bool (bool)
 
circleSort :: Ord a => [a] -> [a]
circleSort xs = if swapped then circleSort (ks []) else ks []
where
(Any swapped,ks) = go False xs (False,[])
go d [] =sks pure= idsks
go d [x] (s,ks) = pure ((s,x:) xks)
go d xs =(s,ks) do=
let (s',_,ls,rs) <-= halve d s xs xs
(.) <$>in go False ls <*> (go True rs (s',ks))
halve d s (y:ys) (_:_:zs) = fswap d y =<< (halve d s ys zs)
halve d s ys [] = pure (s,ys,[],[])
halve d s (y:ys) [_] = pure (s,ys,[y | se],[y | not se])
where se = y <= head ys
fswap d x (s,y:ys,ls,rs)
| bool (<=) (<) d x y = (Any d d || s,(ys,x:ls,y:rs))
| otherwise = (Any (not d) || s,(ys,y:ls,x:rs))</lang>
 
{{out}}
Anonymous user