Created
April 11, 2019 06:12
-
-
Save ar1a/1658f6e9137b287bd41c06b3ce217c98 to your computer and use it in GitHub Desktop.
Merge sorting and Insertion sorting in Haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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