Skip to content

Instantly share code, notes, and snippets.

@mgrabovsky
Created June 27, 2019 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgrabovsky/f849770382716e8b0f78612aa67fc9dd to your computer and use it in GitHub Desktop.
Save mgrabovsky/f849770382716e8b0f78612aa67fc9dd to your computer and use it in GitHub Desktop.
module Melsort (melsort) where
-- TODO: Linked lists are not the best for this algorithm performance-wise.
-- Consider a different structure, perhaps Vector.
-- TODO: Some preconditions are required.
push :: Ord a => a -> [[a]] -> [[a]]
push x [] = [[x]]
push x ([y]:ls) -- TODO: Is it possible that ls /= [] here? It's not.
| x <= y = [x, y ] : ls
| x > y = [ y, x] : ls
push x ([y, z]:ls)
| x <= y = [x, y, z ] : ls
| x >= z = [ y, z, x] : ls
| otherwise = [ y, z ] : push x ls
push x (l:ls)
| x <= head l = (x:l) : ls
| x >= last l = (l ++ [x]) : ls
| otherwise = l : push x ls
-- TODO: Some preconditions are required.
merge :: Ord a => [[a]] -> [a]
merge = foldr merge' []
where
merge' xs [] = xs
merge' (x:xs) (y:ys)
| x <= y = x : merge' xs (y:ys)
| otherwise = y : merge' (x:xs) ys
melsort :: Ord a => [a] -> [a]
melsort = merge . foldr push []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment