Skip to content

Instantly share code, notes, and snippets.

@brunoczim
Last active August 15, 2018 03:58
Show Gist options
  • Save brunoczim/b7585879325259403bceda7a104b952c to your computer and use it in GitHub Desktop.
Save brunoczim/b7585879325259403bceda7a104b952c to your computer and use it in GitHub Desktop.
module Sorting where
-- tail recursive, much better performance
sort :: Ord a => [a] -> [a]
sort xs = loop [xs] [] where
loop [] ys = ys
loop ([] : xss) ys = loop xss ys
loop ((x : xs) : xss) [] = loop (xs : xss) [x]
loop ((x : xs) : xss) (y : ys) = if x <= y
then loop (xs : xss) (x : y : ys)
else loop (reverse (x : ys) : (y : xs) : xss) []
-- shorter, but non tail recursive
sort' :: Ord a => [a] -> [a]
sort' [] = []
sort' (x : xs) = case sort' xs of
[] -> [x]
(y : ys) -> if y < x
then y : sort' (x : ys)
else x : y : ys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment