user
Task

Write a program to find the   median   value of a vector of floating-point numbers.

The program need not handle the case where the vector is empty, but *must* handle the case where there are an even number of elements.   In that case, return the average of the two middle values.

There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle.

Sorting would take at least   O(*n* log*n*).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(*n* log*n*).   The best solution is to use the   selection algorithm   to find the median in   O(*n*)   time.

See also

Quickselect\_algorithm

|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| | Tasks for calculating statistical measures | | | --- | --- | |  | | |  |  |  |  |  | | --- | --- | --- | --- | --- | |  | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic  Averages/Arithmetic mean  Averages/Pythagorean means | Averages/Simple moving average |  | | Geometric | Averages/Pythagorean means |  |  | | Harmonic | Averages/Pythagorean means |  |  | | Quadratic | Averages/Root mean square |  |  | | Circular | Averages/Mean angle  Averages/Mean time of day |  |  | | Median | | Averages/Median |  |  | | Mode | | Averages/Mode |  |  | | Standard deviation | | Statistics/Basic |  | Cumulative standard deviation | | | |

---
assistant
(formerly Perl 6)

**Works with**: Rakudo version 2016.08

```
sub median {
  my @a = sort @_;
  return (@a[(*-1) div 2] + @a[* div 2]) / 2;
}

```

Notes:

* The div operator does integer division. The / operator (rational number division) would work too, since the array subscript automatically coerces to Int, but using div is more explicit (i.e. clearer to readers) as well as faster, and thus recommended in cases like this.
* The \* inside the subscript stands for the array's length (see documentation).

In a slightly more compact way:

```
sub median { @_.sort[(*-1)/2, */2].sum / 2 }

```