Created
May 8, 2015 18:24
-
-
Save neilmayhew/3ab029a6db50357c0317 to your computer and use it in GitHub Desktop.
MergeSort algorithm in F#
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
let mergeSort xs = | |
let wrap x = [x] | |
let rec merge = function | |
| x::xs, y::ys -> if x < y then x :: merge (xs, y::ys) else y :: merge (x::xs, ys) | |
| l, [] -> l | |
| [], m -> m | |
let rec mergePairs = function | |
| (l::m::ns) -> merge (l, m) :: mergePairs ns | |
| ls -> ls | |
let rec mergeAll = function | |
| [] -> [] | |
| [l] -> l | |
| ls -> mergeAll (mergePairs ls) | |
mergeAll (List.map wrap xs);; | |
let genRandomNumbers count = | |
let rnd = System.Random() | |
List.init count (fun _ -> rnd.Next (10000));; | |
printf "%A\n" <| mergeSort (genRandomNumbers 80000);; // OK | |
printf "%A\n" <| mergeSort (genRandomNumbers 100000);; // stack overflow |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment