Last active
October 14, 2018 21:03
-
-
Save wpcarro/f8746b171ae41dff10ff78f88208a2f6 to your computer and use it in GitHub Desktop.
Merge Sort (Haskell)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-------------------------------------------------------------------------------- | |
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