Difference between revisions of "PFP Laboratory 9"
Jump to navigation
Jump to search
(Created page with "== Arrays == == Bubble sort == * Create a function, that sorts an array using the bubble sort algorithm. <syntaxhighlight lang="Haskell">bubbleSort :: Array Int Int -> Arra...") |
|||
Line 11: | Line 11: | ||
<div class="mw-collapsible mw-collapsed" data-collapsetext="Hide solution" data-expandtext="Show solution"> | <div class="mw-collapsible mw-collapsed" data-collapsetext="Hide solution" data-expandtext="Show solution"> | ||
<syntaxhighlight lang="Haskell"> | <syntaxhighlight lang="Haskell"> | ||
− | + | import Data.Array | |
− | import | + | import Data.Array.ST |
− | import | + | import Control.Monad |
− | + | bubbleSort :: Array Int Int -> Array Int Int | |
− | + | bubbleSort myArray = runSTArray $ do | |
− | + | stArray <- thaw myArray | |
− | + | let end = (snd . bounds) myArray | |
− | + | forM_ [1 .. end] $ \i -> do | |
− | + | forM_ [0 .. (end - i)] $ \j -> do | |
− | + | val <- readArray stArray j | |
− | + | nextVal <- readArray stArray (j + 1) | |
− | + | let outOfOrder = val > nextVal | |
− | + | when outOfOrder $ do | |
− | + | writeArray stArray j nextVal | |
− | + | writeArray stArray (j + 1) val | |
− | + | return stArray | |
− | |||
− | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</div> | </div> | ||
<div style="clear:both"></div> | <div style="clear:both"></div> |
Latest revision as of 12:53, 4 November 2022
Arrays
Bubble sort
- Create a function, that sorts an array using the bubble sort algorithm.
bubbleSort :: Array Int Int -> Array Int Int
ghci> elems $ bubbleSort $ listArray (0,5) [8,4,9,6,7,1]
[1,4,6,7,8,9]
import Data.Array
import Data.Array.ST
import Control.Monad
bubbleSort :: Array Int Int -> Array Int Int
bubbleSort myArray = runSTArray $ do
stArray <- thaw myArray
let end = (snd . bounds) myArray
forM_ [1 .. end] $ \i -> do
forM_ [0 .. (end - i)] $ \j -> do
val <- readArray stArray j
nextVal <- readArray stArray (j + 1)
let outOfOrder = val > nextVal
when outOfOrder $ do
writeArray stArray j nextVal
writeArray stArray (j + 1) val
return stArray