我想在Haskell中使用这两个函数实现一个sort函数:
smallest :: (Ord a) => [a] -> a
smallest [] = error "empty list"
smallest [x] = x
smallest (x:xs)
| x < smallest xs = x
| otherwise = smallest xs
insert :: Int -> [Int] -> [Int]
insert x [] = [x]
insert x (y:ys)
| x <= y = x:y:ys
| otherwise = y:insert x ys
我的想法是使用递归在正确的位置插入最小的值但是因为我是Haskell的新手,所以我遇到了一些如何实现它的问题。
答案 0 :(得分:3)
smallest (x:xs)
| x < smallest xs = x
| otherwise = smallest xs
重复列表中每个点的smallest
个查询数量,呈指数级增长。代替:
smallest (x:xs) = min x (smallest xs)
,甚至只是smallest
= minimum
。以下是我可以通过您的功能或类似功能看到的几种类型:
insertionSort [] = []
insertionSort (x:xs) = insert x (insertionSort xs)
这个还需要smallest
来回馈剩下的清单:
selectSmallest :: [Int] -> (Int, [Int])
selectSmallest (x:xs) = let (y, ys) = smallest xs in if x < y
then (x, xs)
else (y, x:ys)
selectionSorta [] = []
selectionSorta xs = let (y, ys) = smallest xs in
y : selectionSorta ys