Last active
August 15, 2018 03:58
-
-
Save brunoczim/b7585879325259403bceda7a104b952c to your computer and use it in GitHub Desktop.
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
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