Last active
October 24, 2024 20:35
-
-
Save bwkam/dd402bb0d13f5f37c5e3eeea9d61ee56 to your computer and use it in GitHub Desktop.
haskell merge sort
This file contains hidden or 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
mergesort :: (Ord a) => [a] -> [a] | |
mergesort xs = | |
let sort :: (Ord a) => [[a]] -> [[a]] | |
sort ys = case list of | |
[a] -> [a] | |
a -> sort a | |
where | |
list = concatAdjacentWith merge ys | |
in concat $ sort (splitEvery 1 xs) | |
merge :: (Ord a) => [a] -> [a] -> [a] | |
merge x [] = x | |
merge [] x = x | |
merge (x : xs) (y : ys) = do | |
case compare x y of | |
GT -> y : merge (x : xs) ys | |
LT -> x : merge xs (y : ys) | |
EQ -> x : y : merge xs ys | |
concatAdjacentWith :: (Ord a) => ([a] -> [a] -> [a]) -> [[a]] -> [[a]] | |
concatAdjacentWith f (x : y : xs) = f x y : concatAdjacentWith f xs | |
concatAdjacentWith _ xs = xs | |
splitEvery :: Int -> [a] -> [[a]] | |
splitEvery _ [] = [] | |
splitEvery n xs = first : splitEvery n rest | |
where | |
(first, rest) = splitAt n xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment