Skip to content

Instantly share code, notes, and snippets.

@wpcarro
Last active October 14, 2018 21:03
Show Gist options
  • Save wpcarro/f8746b171ae41dff10ff78f88208a2f6 to your computer and use it in GitHub Desktop.
Save wpcarro/f8746b171ae41dff10ff78f88208a2f6 to your computer and use it in GitHub Desktop.
Merge Sort (Haskell)
--------------------------------------------------------------------------------
import Data.Function ((&))
--------------------------------------------------------------------------------
main :: IO ()
main =
[2,3,5,1,4,6,8,7,9] & mergeSort & show & putStrLn
mergeSort :: (Ord a) => [a] -> [a]
mergeSort [] = []
mergeSort [x] = [x]
mergeSort xs = merge (mergeSort lhs) (mergeSort rhs)
where
(lhs, rhs) = splitAt (length xs `div` 2) xs
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] rhs = rhs
merge lhs [] = lhs
merge lhs@(x:xs) rhs@(y:ys)
| x <= y = x:(merge xs rhs)
| otherwise = y:(merge lhs ys)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment