Skip to content

Instantly share code, notes, and snippets.

@portnov
Created April 23, 2019 18:09
Show Gist options
  • Save portnov/4c341dc4513fac294857a29e6316b3bf to your computer and use it in GitHub Desktop.
Save portnov/4c341dc4513fac294857a29e6316b3bf to your computer and use it in GitHub Desktop.
bubble sort in haskell
import Control.Monad
import Foreign.Ptr
import Foreign.Marshal.Array
import Foreign.Storable
import Data.Int
type Array a = Ptr a
get :: Storable a => Array a -> Int -> IO a
get array i =
peek (array `plusPtr` i)
set :: Storable a => Array a -> Int -> a -> IO ()
set array i x =
poke (array `plusPtr` i) x
sort :: (Storable a, Ord a) => Int -> Array a -> IO ()
sort size array = forM_ [1 .. size] $ \iteration ->
forM_ [0 .. size-1] $ \i ->
forM_ [i+1 .. size-1] $ \j -> do
x <- get array i
y <- get array j
when (x > y) $ do
set array i y
set array j x
inputArray :: (Storable a, Read a) => Int -> Array a -> IO ()
inputArray size array = forM_ [0 .. size-1] $ \i -> do
x <- read `fmap` getLine
set array i x
printArray :: (Storable a, Show a) => Int -> Array a -> IO ()
printArray size array = forM_ [0 .. size-1] $ \i -> do
x <- get array i
putStrLn $ "[" ++ show i ++ "]" ++ show x
main :: IO ()
main = do
size <- read `fmap` getLine
allocaArray size $ \array -> do
inputArray size (array :: Array Int8)
sort size array
printArray size array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment