Skip to content

Instantly share code, notes, and snippets.

@harpocrates
Created March 23, 2016 18:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harpocrates/bbed7b6837d524aafa02 to your computer and use it in GitHub Desktop.
Save harpocrates/bbed7b6837d524aafa02 to your computer and use it in GitHub Desktop.
module ImperativeQuickSort (quicksort) where
import Prelude hiding (take,drop,length,tail,init)
import Data.Vector (modify,Vector)
import Data.Vector.Generic.Mutable hiding (modify)
-- | Imperative quicksort with O(log n) auxilary space (on top of returned vector)
quicksort :: Ord a => Vector a -> Vector a
quicksort = modify qsort'
where
qsort' vec
| length vec < 2 = return ()
| otherwise = do
middle <- partition vec (length vec - 1)
qsort' $ take middle vec --left
qsort' $ drop (middle + 1) vec --right
partition vec j = do
pivot <- vec `unsafeRead` j
i <- unstablePartition (< pivot) (init vec)
swap vec i j
return i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment