Pseudo-quicksort time complexity

前端 未结 6 1013
不思量自难忘°
不思量自难忘° 2020-12-03 14:31

I know that quicksort has O(n log n) average time complexity. A pseudo-quicksort (which is only a quicksort when you look at it from far enough away, with a sui

6条回答
  •  鱼传尺愫
    2020-12-03 15:10

    This "quicksort" is actually deforested tree sort: http://www.reddit.com/r/programming/comments/2h0j2/real_quicksort_in_haskell

    data Tree a = Leaf | Node a (Tree a) (Tree a)
    
    mkTree [] = Leaf
    mkTree (x:xs) = Node x (mkTree (filter (<= x) xs)) (mkTree (filter (x <) xs))
    

    Binary tree is unbalanced, so O(N^2) worst-case and O(N*Log N) average-case complexity for building search tree.

    foldTree f g Leaf = g
    foldTree f g (Node x l r) = f x (foldTree f g l) (foldTree f g r)
    
    treeSort l = foldTree (\x lft rht -> lft++[x]++rht) [] (mkTree l)
    

    Retrieval algorithm have O(N^2) worst-case and O(N*Log N) average-case complexity.

    Well-balanced:

    Prelude> let rnds = iterate step where step x = (75*x) `mod` 65537
    Prelude> length . quicksort . take 4000 . rnds $ 1
    4000
    (0.08 secs, 10859016 bytes)
    Prelude> length . quicksort . take 8000 . rnds $ 1
    8000
    (0.12 secs, 21183208 bytes)
    Prelude> length . quicksort . take 16000 . rnds $ 1
    16000
    (0.25 secs, 42322744 bytes)
    

    Not-so-well-balanced:

    Prelude> length . quicksort . map (`mod` 10) $ [1..4000]
    4000
    (0.62 secs, 65024528 bytes)
    Prelude> length . quicksort . map (`mod` 10) $ [1..8000]
    8000
    (2.45 secs, 241906856 bytes)
    Prelude> length . quicksort . map (`mod` 10) $ [1..16000]
    16000
    (9.52 secs, 941667704 bytes)
    

提交回复
热议问题