# How to select the median of a list?

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.

• Use Part (shortcut [[ ]]) to take the term that is at the position (Length[list]+1)/2 – bill s Nov 14 '20 at 14:01
• Quantile[{1, 2, 3, 4, 5, 6, 7}, 1/2] – wuyudi Nov 14 '20 at 14:03
• Duplicate. See this question. – Alan Nov 14 '20 at 15:18
• Ummm... just wondering: why not use Median? – David G. Stork Nov 14 '20 at 19:51

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])

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 *)