Skip to content

Instantly share code, notes, and snippets.

@orionll
Created January 1, 2015 13:33
Show Gist options
  • Select an option

  • Save orionll/c7ffed42d6c75ded858a to your computer and use it in GitHub Desktop.

Select an option

Save orionll/c7ffed42d6c75ded858a to your computer and use it in GitHub Desktop.
In-place bubble sort
import Data.Array.ST
import Data.Array.Base
import Control.Monad.ST
sortPair arr (i, j) = do x <- readArray arr i
y <- readArray arr j
if (x > y) then do writeArray arr i y
writeArray arr j x
else return ()
-- e.g. (pairs 3) produces (0,1), (1,2), (2,3), (0,1), (1,2), (0,1)
pairs n = concat [zip [0..n] $ tail [0..n] | n <- [n, n-1 .. 1]]
sortArray :: Ord a => (STArray s Int a) -> ST s ()
sortArray arr = do len <- getNumElements arr
foldr (\p b -> b >> sortPair arr p) (return ()) (pairs $ len-1)
bubbleSort :: Ord a => [a] -> [a]
bubbleSort xs = runST $ do arr <- newListArray (0, length xs - 1) xs -- convert list to mutable array
sortArray arr -- sort array in place
getElems arr -- convert sorted array to list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment