Created
May 13, 2016 05:00
-
-
Save benjic/fc80a95a854a5fe786fe118553b0c451 to your computer and use it in GitHub Desktop.
Haskell MergeSort
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 | |
mergeSort :: (Ord a) => [a] -> [a] | |
mergeSort ns | |
-- Recursively call merge s | |
| length ns > 1 = merge (mergeSort left, mergeSort right) | |
-- This is the base case where recursion stops | |
| otherwise = ns | |
where | |
-- Split the list in half | |
(left, right) = splitAt (length ns `quot` 2) ns | |
-- Define how to merge two lists | |
merge (xs, []) = xs | |
merge ([], ys) = ys | |
-- Any nonzero length set of lists can be combined recursively | |
merge (x:xs, y:ys) = if x < y then x : merge (xs, y:ys) else y : merge (x:xs, ys) | |
main :: IO() | |
main = do | |
let ns = [10, 9, 8, 7, 2, 4, 5, 2, 32, 6, 5, 4, 3, 2, 1] | |
let sortedNs = mergeSort ns | |
print sortedNs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment