Jump to content

Sorting algorithms/Bogosort: Difference between revisions

Line 864:
import Data.Array.IO
import Control.Monad
isSortedisSortedBy :: (Orda -> 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
shuffle :: [a] -> IO [a]
Line 883 ⟶ 884:
newArray :: Int -> [a] -> IO (IOArray Int a)
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 lixs >>= bogosort</lang>bogosortBy f
 
bogosort :: (Ord a) => [a] -> IO [a]
bogosort li | isSorted li = returnbogosortBy li(<)</lang>
| otherwise = shuffle li >>= bogosort</lang>
Example:
<pre>
Cookies help us deliver our services. By using our services, you agree to our use of cookies.