Advertisement
Guest User

Untitled

a guest
Feb 7th, 2021
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import System.Random
  2. import qualified Data.Sequence as S
  3. import qualified Data.List as L
  4. import Data.Foldable(toList)
  5.  
  6. data Tree a = Node !Int (Tree a) !Int [a] !Int (Tree a) | Leaf
  7.  
  8. sort :: (Ord a, RandomGen g) => S.Seq a -> g -> (S.Seq a, g)
  9. sort sq g = (sq', g'')
  10.    where
  11.        (g',g'') = split g
  12.         n = S.length sq
  13.         tree = qsort (toList sq) g'
  14.        lst = map (index tree) [0..n-1]
  15.        sq' = S.fromList lst
  16.        
  17. qsort :: (Ord a, RandomGen g) => [a] -> g -> Tree a
  18. qsort [] g = Leaf
  19. qsort [x] g = Node 0 Leaf 1 [x] 0 Leaf
  20. qsort lst g = Node (length lt) (qsort lt g1) (length eq) eq (length gt) (qsort gt g3)
  21.     where
  22.         n = length lst
  23.         (i,g0) = randomR (0,n-1) g
  24.         (g1,g3) = split g0
  25.         (lt,eq,gt) = part lst (lst!!i)
  26.  
  27. index :: Tree a -> Int -> a
  28. index (Node nL l nE e nR r) n
  29.     | n < nL = l `index` n
  30.     | n - nL < nE = head e
  31.     | otherwise = r `index` (n - nL - nE)
  32.  
  33. part :: Ord a => [a] -> a -> ([a],[a],[a])
  34. part lst x = L.foldl' f ([],[],[]) (reverse lst)
  35.    where
  36.        f (a,b,c) y = case compare y x of
  37.                        LT -> (y:a,b,c)
  38.                        EQ -> (a,y:b,c)
  39.                        GT -> (a,b,y:c)
  40.  
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement