Last active
July 12, 2018 02:37
-
-
Save weefbellington/786c8631fba266ac35f0 to your computer and use it in GitHub Desktop.
mergesort implementation for learning Haskell
This file contains hidden or 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
import Debug.Trace | |
main :: IO() | |
main = do | |
let sorted = mergeSort [6, 5, 3, 1, 8, 7, 2, 4] | |
print sorted | |
mergeSort :: (Ord a, Show a) => [a] -> [a] | |
-- mergeSort lst | trace ("sorting: " ++ show lst) False = undefined | |
mergeSort [] = [] | |
mergeSort [x] = [x] | |
mergeSort list = | |
merge (mergeSort left) (mergeSort right) | |
where (left, right) = partition list | |
partition :: [a] -> ([a], [a]) | |
partition list = | |
splitAt pivot list | |
where pivot = length list `quot` 2 | |
merge :: (Ord a, Show a) => [a] -> [a] -> [a] | |
-- merge first second | trace ("merging: " ++ show first ++ " " ++ show second) False = undefined | |
merge [] [] = [] | |
merge first [] = first | |
merge [] second = second | |
merge left@(x:xs) right@(y:ys) | |
| x > y = x : merge xs right | |
| otherwise = y : merge left ys |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment