【问题标题】:Haskell: Sort listHaskell:排序列表
【发布时间】:2021-09-04 13:53:40
【问题描述】:

我是 Haskell 的新手。我可以修复这个递归函数对数组中的所有整数进行排序吗?如果是,代码应该如何?

isort [] = []
isort [x] = [x]
isort (x:y:xs) = if x <= y then 
                    x:isort (y:xs) 
                else 
                    y:isort (x:xs)

在当前函数中输入

isort [4,3,2,1]

现在作为输出给出

[3,2,1,4]

但应该是的

[1,2,3,4]

【问题讨论】:

  • 您在这里将前两项中最小的一项作为第一个元素。但并不是说这是整个列表中最小的列表。
  • 在 Data.List 模块中,您对列表有几个操作,其中之一是 sort 。 hackage.haskell.org/package/base-4.15.0.0/docs/…

标签: list sorting haskell functional-programming


【解决方案1】:

排序并在数组中插入一个元素

insert x [] = [x]
insert i (x:xs) = if i<=x then
                    i:x:xs
                else 
                    x:insert i xs

整个数组的循环插入函数

isort [] = []
isort (x:xs) = insert x (isort xs)

【讨论】:

    【解决方案2】:

    可能对代码进行最小更改以让这种列表排序是每次选择列表的mymin 并将其作为结果的第一项并在列表上递归,所以:

    mymin :: Ord a => [a] -> (a, [a])
    mymin [x] = (x, [])
    mymin (x:xs)
        | x <= y = (x, xs)  -- select a new minimum
        | otherwise = (y, x:ys)   -- use the minimum of the tail of the list
        where ~(y, ys) = mymin xs

    然后我们可以合作:

    isort :: Ord a => [a] -> [a]
    isort [] = []
    isort xs = y : isort ys
        where (y, ys) = mymin xs

    这是selection sort [wiki] 的实现,因此在O(n2) 中运行。我把它作为练习来实现更快的算法,例如 merge sortTimsort

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-28
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      • 2016-08-03
      • 2021-03-24
      相关资源
      最近更新 更多