This is how I implemented merge-sort in F# using imperative style:
let merge (l1: List<string>, l2: List<string>) =
let r: List<string> = new List<string>()
let mutable (i,j, cnt1, cnt2) = (0,0, l1.Count, l2.Count)
while i < cnt1 && j < cnt2 do
if l1.[i] <= l2.[j] then
r.Add (l1.[i])
i <- i + 1
else
r.Add (l2.[j])
j <- j + 1
if i = cnt1 then
while j < cnt2 do
r.Add (l2.[j])
j <- j + 1
else
while i < cnt1 do
r.Add (l1.[i])
i <- i + 1
r
Can you convert this to alternate ‘functional’ styled implementation and explain how it works, if possible? Even though I am studying list comprehensions and all that at the moment, I can’t come up with an idea to use it here.
You’re using .NET
List<'T>which is renamed to ResizeArray<‘T> in F# to avoid confusion. If you use functional list,mergefunction would look like this:To explain this function in terms of your imperative version:
whileloop where you compare two current elements and add the smaller one into a resulting list.whileloops.i = cnt1andj = cnt2and we should return results. Since a new element is always prepended to the accumulator, we need to reverse it to get a list in the increasing order.To be precise, your
mergefunction is just one part of merge-sort algorithm. You need a function to split a list in two halves, call merge-sort on two halves and merge two sorted halves into one. Thesplitfunction below is left for you as an exercise.