0

If I have a list {3,19.5,85,45/2,5.6}, how can I select the median of the list without using the built-in Median command?

First I sorted the list

Sort[{3,19.5,85,45/2,5.6}]
{3, 5.6, 19.5, 45/2, 85}

I can't figure out which command to use to select the median without directly using Median command.

C. E.
  • 70,533
  • 6
  • 140
  • 264
Rosey
  • 1
  • 1

2 Answers2

2

Just for fun, here's a rendering into Mathematica of a very old idiom from the APL programming language (see https://aplwiki.com/wiki/FinnAPL_idiom_library#cite_note-1) that requires no explicit splitting into odd/even cases:

    myMedian[lis_] := (1/2) Total[Sort[lis][[Abs@Ceiling[{-1/2, 1/2} (1 + Length@lis)]]]]

Tests:

    x = RandomInteger[{2, 50}, RandomInteger[{4, 8}]];
    Sort[x]
    {myMedian[x], Median[x]}
(* {4, 9, 31, 34, 39, 40, 40, 44} *)
(* 73/2, 73/2 *)
x = RandomInteger[{2, 50}, RandomInteger[{4, 8}]];
Sort[x]
{myMedian[x], Median[x]}

(* {2, 16, 16, 18, 24, 26, 42} ) ( 18, 18 *)

murray
  • 11,888
  • 2
  • 26
  • 50
1

If the length of the list is odd, then the median is the middle element of the sorted list. If the length of the list is even, the median is the average of the two "central" values:

myMedian[x_List] := (z = Sort[x];
  len = Length[z];
  If[OddQ[len], z[[(len + 1)/2]], (z[[len/2]] + z[[len/2 + 1]])/2])
David G. Stork
  • 41,180
  • 3
  • 34
  • 96