Created
August 18, 2022 02:40
-
-
Save lborg019/c8e11eb9abff52980f81e56f227f7149 to your computer and use it in GitHub Desktop.
fsharp merge sort
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
let rec split = function | |
| [] -> ([], []) | |
| [a] -> ([a], []) | |
| a::b::cs -> let (M,N) = split cs in (a::M, b::N) | |
let rec merge = function | |
| ([], ys) -> ys | |
| (xs, []) -> xs | |
| (x::xs, y::ys) -> if x < y then x :: merge (xs, y::ys) | |
else y :: merge (x::xs, ys) | |
let rec mergesort = function | |
| [] -> [] | |
| [a] -> [a] //added line | |
| L -> let (M, N) = split L in | |
merge (mergesort M, mergesort N);; | |
(* | |
val mergesort : _arg1:'a list -> 'a list when 'a : comparison | |
Mergesort returns a list that has the same type as it was | |
passed in. | |
> mergesort [2;9;3;1;4;5;8;7;6];; </br> | |
val it : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9] | |
*) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment