Skip to content

Instantly share code, notes, and snippets.

@neilmayhew
Created May 8, 2015 18:24
Show Gist options
  • Save neilmayhew/3ab029a6db50357c0317 to your computer and use it in GitHub Desktop.
Save neilmayhew/3ab029a6db50357c0317 to your computer and use it in GitHub Desktop.
MergeSort algorithm in F#
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