Sorting algorithms/Bogosort: Difference between revisions

Content added Content deleted
Line 864: Line 864:
import Data.Array.IO
import Data.Array.IO
import Control.Monad
import Control.Monad
isSortedBy :: (a -> a -> Bool) -> [a] -> Bool
isSortedBy _ [] = True
isSortedBy f xs = all (uncurry f) . (zip <*> tail) $ xs


isSorted :: (Ord a) => [a] -> Bool
isSorted (e1:e2:r) = e1 <= e2 && isSorted (e2:r)
isSorted _ = True

-- from http://www.haskell.org/haskellwiki/Random_shuffle
-- from http://www.haskell.org/haskellwiki/Random_shuffle
shuffle :: [a] -> IO [a]
shuffle :: [a] -> IO [a]
Line 883: Line 884:
newArray :: Int -> [a] -> IO (IOArray Int a)
newArray :: Int -> [a] -> IO (IOArray Int a)
newArray n xs = newListArray (1,n) xs
newArray n xs = newListArray (1,n) xs
bogosortBy :: (a -> a -> Bool) -> [a] -> IO [a]
bogosortBy _ [] = return []
bogosortBy f xs | isSortedBy f xs = return xs
| otherwise = shuffle xs >>= bogosortBy f


bogosort :: (Ord a) => [a] -> IO [a]
bogosort :: Ord a => [a] -> IO [a]
bogosort li | isSorted li = return li
bogosort = bogosortBy (<)</lang>
| otherwise = shuffle li >>= bogosort</lang>
Example:
Example:
<pre>
<pre>