Advertisement
Guest User

Untitled

a guest
Dec 24th, 2013
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. {-# OPTIONS_GHC -O2 -optc-O2 #-}
  2. module Main where
  3.  
  4. import Control.Monad
  5. import Control.Monad.State
  6. import Data.List (foldl1')
  7.  
  8. data Heap a = Leaf
  9. | Node Int a (Heap a) (Heap a)
  10.  
  11. weight :: (Ord a) => Heap a -> Int
  12. weight Leaf = 0
  13. weight (Node w _ _ _) = w
  14.  
  15. make :: (Ord a) => a -> Heap a -> Heap a -> Heap a
  16. make x l r | wl < wr = Node (wl + 1) x r l
  17. | otherwise = Node (wr + 1) x l r
  18. where wl = weight l
  19. wr = weight r
  20.  
  21. singleton :: (Ord a) => a -> Heap a
  22. singleton x = Node 1 x Leaf Leaf
  23.  
  24. merge :: (Ord a) => Heap a -> Heap a -> Heap a
  25. merge h1 Leaf = h1
  26. merge Leaf h2 = h2
  27. merge h1@(Node w1 x1 l1 r1) h2@(Node w2 x2 l2 r2)
  28. | x1 < x2 = make x1 l1 (merge r1 h2)
  29. | otherwise = make x2 (merge h1 l2) r2
  30.  
  31. extractMin :: (Ord a) => Heap a -> (a, Heap a)
  32. extractMin Leaf = undefined
  33. extractMin (Node _ x l r) = (x, merge l r)
  34.  
  35. heapSort :: (Ord a) => [a] -> [a]
  36. heapSort [] = []
  37. heapSort xs = fst . flip runState h . replicateM n $ state extractMin
  38. where n = length xs
  39. h = foldl1' merge $ map singleton xs
  40.  
  41. main :: IO ()
  42. main = do
  43. let n = 1000000
  44. vs = [n, n - 1 .. 0]
  45. if (reverse vs) == heapSort vs
  46. then putStrLn "OK"
  47. else putStrLn "FAIL"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement