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.5s)一起指定。但你仍然可以感受到不同之處。緩慢插入排序
可能是問題是insert
函數或firstns ++ (x:other)
中的每個分支的執行過於緩慢。但無論如何,爲了把這個項目放在列表的最後,我需要瀏覽O(n)的整個列表。
這是什麼問題? –
'insertionSortIter'遍歷O(n)個位置,並在每次迭代中調用O(n)時間的'!!'運算符,使得它僅僅插入一個單獨的項目(O ^^)。不要這樣做。 –
ДМИТРИЙ,很高興在那裏見到你。爲什麼這麼慢。我究竟做錯了什麼。 – vlastachu