Skip to content

Instantly share code, notes, and snippets.

@ar1a
Created April 11, 2019 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ar1a/1658f6e9137b287bd41c06b3ce217c98 to your computer and use it in GitHub Desktop.
Save ar1a/1658f6e9137b287bd41c06b3ce217c98 to your computer and use it in GitHub Desktop.
Merge sorting and Insertion sorting in Haskell
module Main where
main :: IO ()
main = pure ()
-- Source: https://youtu.be/PV8_scc1s3g
-------------------------------------------------------------------------------
-- insertion sort --
-------------------------------------------------------------------------------
-- Insert an element in a sorted list
insert :: Int -> [Int] -> [Int]
insert x [] = [x]
insert x (y:ys)
| x <= y = x : y : ys
| otherwise = y : insert x ys
-- insert sort a list
isort :: [Int] -> [Int]
-- isort [] = []
-- isort (x:xs) = insert x (isort xs)
isort = foldr insert []
-------------------------------------------------------------------------------
-- merge sort --
-------------------------------------------------------------------------------
-- Merge two sorted lists
merge :: [Int] -> [Int] -> [Int]
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
| x <= y = x : merge xs (y : ys)
| otherwise = y : merge (x : xs) ys
mergesort :: [Int] -> [Int]
mergesort [] = []
mergesort [x] = [x]
mergesort l = merge (mergesort (front l)) (mergesort (back l))
where
front l = take (length l `div` 2) l
back l = drop (length l `div` 2) l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment