合并排序
订购两个有序列表的合并
保留重复:
merge::Ord a => [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) | x <= y = x:merge xs (y:ys)
| otherwise = y:merge (x:xs) ys
自上而下版本:
msort::Ord a => [a] -> [a]
msort [] = []
msort [a] = [a]
msort xs = merge (msort (firstHalf xs)) (msort (secondHalf xs))
firstHalf xs = let { n = length xs } in take (div n 2) xs
secondHalf xs = let { n = length xs } in drop (div n 2) xs
为了清晰起见,这种方式被定义,而不是为了效率。
使用示例:
> msort [3,1,4,5,2]
结果:
[1,2,3,4,5]
自下而上版本:
msort [] = []
msort xs = go [[x] | x <- xs]
where
go [a] = a
go xs = go (pairs xs)
pairs (a:b:t) = merge a b : pairs t
pairs t = t