繁体   English   中英

Haskell:排序列表

[英]Haskell: Sort list

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

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

输入电流 function

isort [4,3,2,1]

现在给出 output

[3,2,1,4]

但应该是

[1,2,3,4]

可能对代码进行这种排序的最小更改是每次选择列表的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

这是选择排序[wiki]的一个实现,因此在O(n 2 )中运行。 我把它留作练习,以实现更快的算法,如合并排序Timsort

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

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

在整个数组上循环插入 function

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM