Search code examples
ocamlmedian

Function that returns the median? (OCaml)


In OCaml how would I write a median function that takes 5 arguments and returns the median. For example med5 2 5 7 4 3 would return 4.

I managed to write a med3 function (returns the median of 3 arguments) using if and else statements but this would be ridiculously complex if I attempted the same technique for 5 arguments :(

let med3 a b c =
  if ((b<=a && c>=a) || (c<=a && b>=a)) then a 
  else if ((a<=b && c>=b) || (c<=b && a>=b)) then b else c;;

For the med5 function, I would like to be able to use the min and max functions (built in to OCaml) to discard the highest and lowest values from the set of 5 arguments. Then I could use the med3 function that I have already written to return the median of the remaining 3 arguments, but how do I discard the minimum and maximum arguments!?!?!?!?

Any help would be much appreciated :)


Solution

  • If you can use Array, then just put your 5 entries in an array, sort it, and return a[2]. If it's also forbidden in your assignment, you can use a poor-man's bubble sort to select the max, then the min:

    let med5 a b c d e =
      (* move the max towards 'e' *)
      let a,b = if a<=b then a,b else b,a in
      let b,c = if b<=c then b,c else c,b in
      ...
      (* then move the min towards 'd', don't forget to reverse the comparisons *)
      ...
      in med3 a b c