Created
November 21, 2011 07:02
-
-
Save uiur/1381892 to your computer and use it in GitHub Desktop.
Haskellのれんしゅう: マージソート
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
-- Merge Sort | |
msort :: (Ord a) => [a] -> [a] | |
msort [] = [] | |
msort [x] = [x] | |
msort xs = merge (msort f) (msort s) | |
where | |
(f,s) = split xs | |
split :: (Ord a) => [a] -> ([a],[a]) | |
split xs = splitAt center xs | |
where | |
center = (length xs) `div` 2 | |
merge :: (Ord a) => [a] -> [a] -> [a] | |
merge xs [] = xs | |
merge [] ys = ys | |
merge xs'@(x:xs) ys'@(y:ys) | |
| x < y = x : merge xs ys' | |
| otherwise = y : merge xs' ys | |
-- Test | |
main = do | |
print $ msort [4,3,1,2,7,5] | |
print $ msort ["catch","fax","cat","dog","fox"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment