Advertisement
NLinker

Space-efficient in-place quicksort

Sep 28th, 2016
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE ScopedTypeVariables #-}
  2. module QuickSort where
  3.  
  4. import           Control.Monad
  5. import           Control.Monad.Primitive
  6. import           Data.List
  7. import qualified Data.Vector                 as V
  8. import qualified Data.Vector.Mutable         as MV
  9. import           Data.Vector.Unboxed         hiding (filter, forM_, head,
  10.                                               reverse, tail, (++))
  11. import qualified Data.Vector.Unboxed.Mutable as M
  12. import           Test.QuickCheck
  13. import           Test.QuickCheck.Instances
  14.  
  15. qs :: Ord a => [a] -> [a]
  16. qs [] = []
  17. qs (x:xs) = qs left ++ [x] ++ qs right
  18.   where
  19.      left  = filter (<x) xs
  20.      right = filter (>=x) xs
  21.  
  22. quickSort :: Vector Int -> Vector Int
  23. quickSort = modify f
  24.   where
  25.     f :: (Ord a, PrimMonad m, Unbox a) => MVector (PrimState m) a -> m ()
  26.     f v = qsort v 0 (M.length v - 1)
  27.       where
  28.         qsort a low high =
  29.           when (low < high) $ do
  30.             p <- partition a low high
  31.             qsort a low (p - 1)
  32.             qsort a (p + 1) high
  33.  
  34.         partition a low high = do
  35.           pivot <- M.read a high
  36.           go low (high-1) low pivot a
  37.  
  38.         go l h i pivot a =
  39.           if l <= h
  40.             then do
  41.                aj <- M.read a l
  42.                if aj <= pivot
  43.                  then do
  44.                    M.swap a l i
  45.                    go (l+1) h (i+1) pivot a
  46.                  else
  47.                    go (l+1) h i pivot a
  48.             else do
  49.               M.swap a (h+1) i
  50.               return i
  51.  
  52. test = quickCheck $ \(v :: Vector Int) ->
  53.   (quickSort v) == (fromList $ sort (toList v))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement