Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 什么';用一系列反转对数组排序最有效的方法是什么?_Algorithm_Sorting_Haskell_Recursion_Graph Algorithm - Fatal编程技术网

Algorithm 什么';用一系列反转对数组排序最有效的方法是什么?

Algorithm 什么';用一系列反转对数组排序最有效的方法是什么?,algorithm,sorting,haskell,recursion,graph-algorithm,Algorithm,Sorting,Haskell,Recursion,Graph Algorithm,我有一个已经按降序排序的整数列表,但是应用了一个函数,该函数取第一个元素的值(我们称之为x),并将减去1映射到列表其余部分(不包括第一个元素)的x值。(我正在尝试实现递归算法以检查是否存在错误。) 新列表需要按降序再次排序,以便进行下一步递归。我尝试过使用Data.List.sort,但对于大型列表来说,这会变得相当慢,因为它适用于每一级递归 将subtract 1映射到非递增整数列表开头的性质意味着实际上只有一个点存在反转:例如,在前一个代码中,前两个1只需与下两个2交换即可对列表进行排序 最

我有一个已经按降序排序的整数列表,但是应用了一个函数,该函数取第一个元素的值(我们称之为
x
),并将
减去1
映射到列表其余部分(不包括第一个元素)的
x
值。(我正在尝试实现递归算法以检查是否存在错误。)

新列表需要按降序再次排序,以便进行下一步递归。我尝试过使用
Data.List.sort
,但对于大型列表来说,这会变得相当慢,因为它适用于每一级递归

subtract 1
映射到非递增整数列表开头的性质意味着实际上只有一个点存在反转:例如,在前一个代码中,前两个
1
只需与下两个
2
交换即可对列表进行排序


最有效(即最快)的排序方式是什么?此外,是否有一种更有效的数据结构可用于此作业而不是列表?

您最好使用运行长度编码。这样你就不必挖得太远来保持列表的有序

(警告:未经测试的Haskell代码。)函数

rlEncode xs = [(length xs', head xs') | xs' <- reverse $ group $ sort xs]
还有一个“析构函数”

用于运行长度编码列表。然后,
isGraphic
,以其最简单和最低效的形式,看起来是这样的

isGraphic [] = True
isGraphic rle = fromMaybe False $ do
    (d, rle') <- rlUncons rle
    rle'' <- deflate d rle'
    return $ isGraphic rle''

deflate 0 rle = Just rle
deflate _d [] = Nothing
deflate _d [(_,0)] = Nothing
deflate d ((n, d') : rle)
    | d < n = Just $ rlCons (n - d, d') $ rlCons (d, d' - 1) rle
    | otherwise = liftM (rlCons (n, d' - 1)) $ deflate (d - n) rle
isGraphic[]=True
isGraphic rle=fromFalse$do

(d,rle')合并是将两个排序的lists@JonathanJeffrey作为文章作者,我可以单方面批准你的建议编辑,但你不应该养成在建议编辑中更改代码的习惯,因为审阅它们的人没有上下文,并且被指示不要批准似乎改变作者意图的编辑。好的,谢谢!作为一个补充说明,我认为在deflate函数中使用
mod
跳过递归地对同一个数字进行泄气,也就是说,添加大小写
d==d'&&drlCons(0,u)rle=rle
。谢谢你的帮助!
rlCons (n, x) [] = [(n, x)]
rlCons (n, x) rle@((n', x') : rle')
    | x == x' = (n + n', x) : rle'
    | otherwise = (n, x) : rle
rlUncons [] = Nothing
rlUncons ((1, x) : rle) = Just (x, rle)
rlUncons ((n, x) : rle) = Just (x, (n - 1, x) : rle)
isGraphic [] = True
isGraphic rle = fromMaybe False $ do
    (d, rle') <- rlUncons rle
    rle'' <- deflate d rle'
    return $ isGraphic rle''

deflate 0 rle = Just rle
deflate _d [] = Nothing
deflate _d [(_,0)] = Nothing
deflate d ((n, d') : rle)
    | d < n = Just $ rlCons (n - d, d') $ rlCons (d, d' - 1) rle
    | otherwise = liftM (rlCons (n, d' - 1)) $ deflate (d - n) rle