Take the 2-minute tour ×

Need some advice with OCaml and finding median of five arguments(I'm a complete beginner with this language)

So far I have

let med5 x1 x2 x3 x4 x5 = if x1<=x2 then x1,x2 else x2,x1; if x2<=x3 then x2,x3 else x3,x2...   

Am I on the right path?

share|improve this question

2 Answers 2

up vote 0 down vote accepted

Generally speaking this code seems to be on the right track. However, your code is returning a pair of numbers. Eventually you'll want the code to return a single number.

To solve this problem with close to the smallest number of comparisions seems quite hard. There are 120 different orders of 5 numbers and you need to track some sizeable fraction of them.

To keep the number of possibilities smaller you can sort all the numbers and take the middle one. Or you could maybe sort some groups of numbers and work from there.

Here's some code that figures out the median of 3 numbers by sorting two of them then figuring out where the third one is.

let med3 a b c =
    let (l, h) = if a < b then (a, b) else (b, a) in
    if c < l then l else if c > h then h else c
share|improve this answer

Figure out the order of the first three elements, then call a function that uses that ordering information to finish the job:

let min3 a b c = min (min a b) c
let max3 a b c = max (max a b) c

(* First three arguments in order *)
let median5_3 a b c d e =
  assert (a <= b && b <= c);
  if d < b then
    if e < b then max3 a d e else b
    if e < b then b else min3 c d e

let median5 a b c d e =
  if a < b then
    if a < c then
      if b < c then median5_3 a b c d e
      else median5_3 a c b d e
    else median5_3 c a b d e
    if b < c then
      if a < c then median5_3 b a c d e
      else median5_3 b c a d e
    else median5_3 c b a d e

(This is straight out of Stepanov's Notes on Programming, by the way.)

share|improve this answer

Your Answer


