Skip to content

Instantly share code, notes, and snippets.

@weefbellington
Last active July 12, 2018 02:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weefbellington/786c8631fba266ac35f0 to your computer and use it in GitHub Desktop.
Save weefbellington/786c8631fba266ac35f0 to your computer and use it in GitHub Desktop.
mergesort implementation for learning Haskell
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