缓慢插入排序

时间:2013-08-18 13:35:56

标签: haskell mergesort insertion-sort

insertionSort :: (Ord a) => [a] -> [a]
insertionSort (x:xs) = insertionSortIter [x] xs 
    where insertionSortIter sorted []      =  sorted  
          insertionSortIter sorted (x:xs)  =  insertionSortIter (insert x sorted (length sorted)) xs
          insert x list n   --insert x in list at n
                | n == 0    = x:list
                | x < list !! (n - 1)   = insert x list (n - 1)
                | otherwise = firstns ++ (x:other) where (firstns, other) = splitAt n list
-- [1..10000] 30s                    
mergeSort :: (Ord a) => [a] -> [a]
mergeSort (x:[])      = [x]
mergeSort  list       = merge (mergeSort list1) (mergeSort list2)
        where (list1, list2) = splitAt (length list `div` 2) list
              merge [] list       = list
              merge list []       = list
              merge (x:xs) (y:ys) = if x < y then x:(merge xs (y:ys)) else y:(merge (x:xs) ys)
-- [1..10000] 2.4s

执行时间由建筑时间(1或1.5秒)指定。但你仍然可以感受到它的不同。

问题可能是insert函数或firstns ++ (x:other)保护的每个分支的执行速度太慢。但无论如何,要将项目放在列表的末尾,我需要浏览整个O(n)列表。

1 个答案:

答案 0 :(得分:2)

您的insert功能很慢。以下是插入排序的方法:

insertionSort :: Ord a => [a] -> [a]
insertionSort xs = f [] xs
  where
    f rs []     = rs
    f rs (x:xs) = f (insert x rs) xs

    insert x []         = [x]
    insert x rrs@(r:rs) = if x < r then x:rrs else r:insert x rs

如果出现混淆,rrs@(r:rs)语法表示rrs是整个列表,r是其头部,rs是其尾部。

insert遍历列表并输出应该在x前面的所有元素,然后它会输出x后跟应该在之后的元素x