Skip to content

Instantly share code, notes, and snippets.

@simonh1000
Created October 26, 2014 08:17
Show Gist options
  • Save simonh1000/d0f6a17e5e862c19cb33 to your computer and use it in GitHub Desktop.
Save simonh1000/d0f6a17e5e862c19cb33 to your computer and use it in GitHub Desktop.
QuickSort using mutable STArray
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Array
qsort :: (STArray s Int Int) -> Int -> Int -> ST s ()
qsort arr min mx =
if mx - min < 1 then
return ()
else do
p <- readArray arr min
final_i <- foldM (partitioner p) (min+1) [(min+1)..mx]
swap min $ final_i - 1
qsort arr min (final_i-2)
qsort arr final_i mx
where
swap i j = do
arr_i <- readArray arr i
arr_j <- readArray arr j
writeArray arr i arr_j
writeArray arr j arr_i
partitioner p i idx = do
arr_idx <- readArray arr idx
if arr_idx > p then
return i
else do
swap i idx
return $ i+1
main = do
lines <- BS.lines `fmap` BS.readFile "10.txt"
let
inputData = Prelude.map (maybe (error "can't read Int") fst . BS.readInt) lines
--inputData = [1,10,4,3,2]
print $ elems $ runSTArray $ do
--newListArray :: (MArray a e m, Ix i) => (i, i) -> [e] -> m (a i e)
state <- newListArray (1, length inputData) inputData
qsort state 1 (length inputData)
return state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment