Created
December 8, 2021 04:29
-
-
Save TylerLeite/6582640425e10af94dc114225d8ec261 to your computer and use it in GitHub Desktop.
haskell merge sort
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
arr = [x*97 `mod` 61 - 30 | x <- [1..20]] | |
-- expecting rhs and lhs to be sorted | |
merge :: Ord a => [a] -> [a] -> [a] -> [a] | |
merge lhs rhs sorted = | |
if length lhs == 0 && length rhs == 0 then | |
sorted | |
else if length lhs == 0 || (length rhs > 0) && head rhs < head lhs then | |
merge (tail rhs) lhs (sorted ++ [head rhs]) | |
else | |
merge rhs (tail lhs) (sorted ++ [head lhs]) | |
sort :: Ord a => [a] -> [a] | |
sort ls = | |
if length ls == 1 then | |
ls | |
else | |
merge (sort (drop n ls)) (sort (take n ls)) [] | |
where n = (length ls) `div` 2 | |
main :: IO () | |
main = putStrLn (show (sort arr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment