Advertisement
Guest User

Untitled

a guest
Dec 24th, 2013
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. {-# OPTIONS_GHC -O2 -optc-O2 #-}
  2. import Control.Monad
  3. import Control.Monad.ST
  4. import Data.Array.ST
  5.  
  6. type Buffer s = STUArray s Int Int
  7.  
  8. left :: Int -> Int
  9. left ix = 2 * ix + 1
  10.  
  11. right :: Int -> Int
  12. right ix = 2 * ix + 2
  13.  
  14. tryRead :: Int -> Int -> Buffer s -> ST s Int
  15. tryRead ix n b = if ix < n
  16. then readArray b ix
  17. else return maxBound
  18.  
  19. heapify :: Int -> Int -> Buffer s -> ST s ()
  20. heapify ix n b = do
  21. let lx = left ix
  22. rx = right ix
  23. iv <- readArray b ix
  24. lv <- tryRead lx n b
  25. rv <- tryRead rx n b
  26. if lv < rv && lv < iv
  27. then writeArray b ix lv >> writeArray b lx iv >> heapify lx n b
  28. else if rv < lv && rv < iv
  29. then writeArray b ix rv >> writeArray b rx iv >> heapify rx n b
  30. else return ()
  31.  
  32. heapSort :: [Int] -> [Int]
  33. heapSort [] = []
  34. heapSort xs = runST $ do
  35. let n = length xs
  36. b <- newListArray (0, n - 1) xs :: ST s (Buffer s)
  37. forM_ [(div n 2), (div n 2) - 1 .. 0] $ \i -> heapify i n b
  38. forM [n, n - 1 .. 1] $ \n -> do
  39. x <- readArray b 0
  40. x' <- readArray b (n - 1)
  41. writeArray b 0 x'
  42. heapify 0 n b
  43. return x
  44.  
  45. main :: IO ()
  46. main = do
  47. let n = 1000000
  48. vs = [n, n - 1 .. 0]
  49. if (reverse vs) == heapSort vs
  50. then putStrLn "OK"
  51. else putStrLn "FAIL"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement