我已经设法在几行中实现了插入排序和快速排序,但是选择排序和合并排序仍然让我头疼;)
selectionsort [] = []
selectionsort (x:xs) =
let (minimum, greater) = extractMinimum x [] xs
in minimum : selectionsort greater
extractMinimum minimumSoFar greater [] = (minimumSoFar, greater)
extractMinimum minimumSoFar greater (x:xs)
| x < minimumSoFar = extractMinimum x (minimumSoFar:greater) xs
| otherwise = extractMinimum minimumSoFar (x:greater) xs
是否有类似extractMinimum
标准库中可用的功能?我试着兜售(a -> a -> Bool/Ordering) -> [a] -> (a, [a])
没有任何运气。
mergesort [ ] = [ ]
mergesort [x] = [x]
mergesort xs =
let (left, right) = splitAt (length xs `div` 2) xs
in merge (mergesort left) (mergesort right)
merge xs [] = xs
merge [] ys = ys
merge xxs@(x:xs) yys@(y:ys)
| x < y = x : merge xs yys
| otherwise = y : merge xxs ys
同样,我必须自己编写merge
,还是可以重用现有组件?Hoogle 没有给我任何有用的结果(a -> a -> Bool/Ordering) -> [a] -> [a] -> [a]
。