Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write mergesort in F#: A merge sort works as follows recursively: (1) Divide the

ID: 3846855 • Letter: W

Question

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

Please find my implementation.

let split (arr : _ array) =
let n = arr.Length
arr.[0..n/2-1], arr.[n/2..n-1]

let rec merge (l : 'a array) (r : 'a array) =
let n = l.Length + r.Length
let res = Array.zeroCreate<'a> n
let mutable i, j = 0, 0
for k = 0 to n-1 do
if i >= l.Length then res.[k] <- r.[j]; j <- j + 1
elif j >= r.Length then res.[k] <- l.[i]; i <- i + 1
elif l.[i] < r.[j] then res.[k] <- l.[i]; i <- i + 1
else res.[k] <- r.[j]; j <- j + 1

res

let rec mergeSort = function
| [||] -> [||]
| [|a|] -> [|a|]
| arr -> let (x, y) = split arr
merge (mergeSort x) (mergeSort y)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote