您将如何对单个链接列表进行排序。(这里的问题是单一属性+使用LinkedList进行排序比数组难)我想看一个伪代码。
尝试使其在时间和空间上都尽可能高效。
谢谢!
合并排序仅涉及几个简单步骤:
检查列表是否为空或具有单个元素。如果是这样,则返回列表不变。
将列表分成两半。合并两个部分。
通过重复从两个列表中删除较小的元素来合并列表。由于零件列表已经排序,因此只需查看两个列表中的第一个元素并选择较小的即可。
返回合并列表。
结果,您将获得一个按最小元素顺序排序的链表。
Haskell中的代码示例:
import Data.List(splitAt) --Mergesorts a list by smallest element first. sort :: Ord a => [a] -> [a] sort = sortBy (<) --Generic sort that can sort in any order. sortBy :: (a -> a -> Bool) -> [a] -> [a] sortBy _ [] = [] sortBy _ [x] = [x] sortBy f xs = merge f (sortBy f first) (sortBy f second) where (first,second) = split xs --Splits a list in half. split :: [a] -> ([a],[a]) split xs = splitAt (halfLength xs) xs --Returns a lists length divided by two as a whole number (rounded). halfLength :: [a] -> Int halfLength = round . (/2) . fromIntegral . length --Merges two lists in the provided order. merge :: (a -> a -> Bool) -> [a] -> [a] -> [a] merge _ [] [] = [] merge _ [] (y:ys) = y:ys merge _ (x:xs) [] = x:xs merge f (x:xs) (y:ys) = if f x y then x : merge f xs (y:ys) else y : merge f (x:xs) ys