Archive for June, 2009

Merging arrays

Thanks to interviewpattern.com I discovered that one of the classical Amazon interview questions is writing a snippet of code to merge two sorted arrays:

“Suppose we have two sorted arrays A[] of m elements and B[] of n elements. Write a function merge which would merge this two arrays into new sorted array C[] in O(n) time as shown on the picture”.

MergeArrays

This problem is also a classical exercise for functional programming learners that shows the conciseness of functional code in comparison with imperative one.

The solution presented on the original page is written in C# and is longer than 40 lines of code, while we can solve the same problem in F# with less than 10 lines:

let rec merge_arrays a b =
  match (a, b) with
  | (a, []) -> a
  | ([], b) -> b
  | (x::xs, y::ys) -> if (x < y) then
                        (x :: (merge_arrays xs (y::ys)))
                      else
                        (y :: (merge_arrays (x::xs) ys))

Besides being shorter, I also find the functional code to be much easier to understand. Do you agree with me?

11 Comments »

claudio on June 13th 2009 in Functional programming