Code Language is F# Write mergesort in F#: A merge sort works as follows recursi
ID: 3848375 • Letter: C
Question
Code Language is F#
Write mergesort in F#: A merge sort works as follows recursively: (1) Divide the unsorted list into two sublists; (2) Sort the two sublists (3) Merge two sorted sublists to produce a new sorted list. Use the split function in Homework #3 to accomplish step (1); Write a recursive function merge to merge to sorted sublists into one sorted list to do (3); Write a recursive function mergesort, which uses the split function to obtain two unsorted sublists from one unsorted list, recursively calls itself on the two unsorted sublists, and then uses merge to get the final sorted list.Explanation / Answer
Let's try this. If you find any difficulties please leave a comment.
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 " <| mergeSort (genRandomNumbers 80000);; // OK
printf "%A " <| mergeSort (genRandomNumbers 100000);; //