Haskell递归排序函数

时间:2017-06-11 10:34:41

标签: sorting haskell

我想在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的新手,所以我遇到了一些如何实现它的问题。

1 个答案:

答案 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