Sorting Haskell中的递归插入排序函数
我有递归插入排序函数的工作代码。我只需要澄清一下它是如何工作的。现在,我对第三行的insert(isort xs)内容感到困惑。如果可以,请一步一步地解释代码的其余部分。 谢谢Sorting Haskell中的递归插入排序函数,sorting,haskell,recursion,insertion,Sorting,Haskell,Recursion,Insertion,我有递归插入排序函数的工作代码。我只需要澄清一下它是如何工作的。现在,我对第三行的insert(isort xs)内容感到困惑。如果可以,请一步一步地解释代码的其余部分。 谢谢 isort::[Int]->[Int] isort[]=[] isort[x]=[x] isort(x:xs)=插入(isort-xs) 其中插入[]=[x] 插入(y:ys) |x
isort::[Int]->[Int]
isort[]=[]
isort[x]=[x]
isort(x:xs)=插入(isort-xs)
其中插入[]=[x]
插入(y:ys)
|x
好的,我们来看看。你说你已经理解了大部分内容,但为了完整起见,我还是会把剩下的部分讲一遍
isort :: [Int] -> [Int]
整数排序获取并返回Int
的列表
isort [] = []
尾部递归函数的基本情况是:空列表被排序。在实践中,对空列表进行排序是很简单的,我们从不关心它,非空列表上的递归总是在这一个之前到达下一个基本情况,因此此行主要是为了让模式保护覆盖所有可能的列表
isort [x] = [x]
单例列表是按重复顺序排序的。这是我们将在实践中达到的基本情况
isort (x:xs) = insert (isort xs)
现在我们进入你问的那条线。这是递归的情况。它调用列表尾部定义的insert
函数。您可以将列表的标题x
看作insert
的一个隐藏参数
此函数基本上对列表的尾部排序,然后将头部插入排序后的列表:
where
insert [] = [x]
将x
插入空列表将生成一个单例列表
insert (y:ys)
| x < y = x : y : ys
| otherwise = y : insert ys
再次浏览
[3,2,1]
示例的区别在于,它从左到右,首先生成[3]
,然后插入2
以获得[2,3]
,然后插入1
以获得[1,2,3]
。累加参数是严格的,它进行的所有调用都是尾部调用,因此它应该更快,同时需要更少的内存。insert
helper函数本身就是尾部递归模cons。处理递归时不要想得太深,让递归本身去想。让我们首先澄清一下isort
,insert
的作用
isort xs
排序列表xs
按递增顺序排列insert(isort-xs)
尝试将单个元素x
插入已排序的列表中:isort-xs
insert(y:ys)
尝试为x
y:ys
的顺序是递增的李>
x=y
,x
应该出现在x
之后,因此我们转到一个子问题:insert ys
insert (y:ys)
| x < y = x : y : ys
| otherwise = y : insert ys
import Data.List (foldl')
insertSort :: Ord a => [a] -> [a]
insertSort = foldl' insert [] where
insert [] x = [x]
insert (y:ys) x | x <= y = x:y:ys
| otherwise = y:(insert ys x)