Averages/Median: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1:
{{task|Probability and statistics}}
[[Category:Sorting]]
[[Category:E examples needing attention]]
{{task|Probability and statistics}}
 
;Task
{{task heading}}
 
Write a program to find the   [[wp:Median|median]]   value of a vector of floating-point numbers.
Line 20 ⟶ 21:
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F median(aray)
V srtd = sorted(aray)
V alen = srtd.len
Line 36 ⟶ 37:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang=Action"action!">INCLUDE "H6:REALMATH.ACT"
 
DEFINE PTR="CARD"
Line 118 ⟶ 119:
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Float_Text_IO;
 
procedure FindMedian is
Line 151 ⟶ 152:
 
=={{header|ALGOL 68}}==
{{trans|C}}<syntaxhighlight lang="algol68">INT max_elements = 1000000;
# Return the k-th smallest item in array x of length len #
Line 226 ⟶ 227:
=={{header|AntLang}}==
AntLang has a built-in median function.
<syntaxhighlight lang=AntLang"antlang">median[list]</syntaxhighlight>
 
=={{header|APL}}==
<syntaxhighlight lang=APL"apl">median←{v←⍵[⍋⍵]⋄.5×v[⌈¯1+.5×⍴v]+v[⌊.5×⍴v]} ⍝ Assumes ⎕IO←0</syntaxhighlight>
 
First, the input vector ⍵ is sorted with ⍵[⍋⍵] and the result placed in v. If the dimension ⍴v of v is odd, then both ⌈¯1+.5×⍴v and ⌊.5×⍴v give the index of the middle element. If ⍴v is even, ⌈¯1+.5×⍴v and ⌊.5×⍴v give the indices of the two middle-most elements. In either case, the average of the elements at these indices gives the median.
 
Note that the index origin ⎕IO is assumed zero. To set it to zero use: <syntaxhighlight lang=APL"apl">⎕IO←0</syntaxhighlight>
 
If you prefer an index origin of 1, use this code instead:
<syntaxhighlight lang=APL"apl">
⎕IO←1
median←{v←⍵[⍋⍵] ⋄ 0.5×v[⌈0.5×⍴v]+v[⌊1+0.5×⍴v]}
Line 276 ⟶ 277:
=={{header|AppleScript}}==
===By iteration===
<syntaxhighlight lang="applescript">set alist to {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}
set med to medi(alist)
 
Line 322 ⟶ 323:
 
{{output}}
<syntaxhighlight lang="applescript">4.5</syntaxhighlight>
 
===Composing functionally===
Line 328 ⟶ 329:
{{Trans|JavaScript}}
{{Trans|Haskell}}
<syntaxhighlight lang=AppleScript"applescript">-- MEDIAN ---------------------------------------------------------------------
 
-- median :: [Num] -> Num
Line 435 ⟶ 436:
end uncons</syntaxhighlight>
{{Out}}
<syntaxhighlight lang=AppleScript"applescript">{missing value, 4, 3.5, 2.1}</syntaxhighlight>
 
----
 
===Quickselect===
<syntaxhighlight lang="applescript">-- Return the median value of items l thru r of a list of numbers.
on getMedian(theList, l, r)
if (theList is {}) then return theList
Line 517 ⟶ 518:
<pre>{|numbers|:{71.6, 44.8, 45.8, 28.6, 96.8, 98.4, 42.4, 97.8}, median:58.7}</pre>
===Partial heap sort===
<syntaxhighlight lang="applescript">-- Based on the heap sort algorithm ny J.W.J. Williams.
on getMedian(theList, l, r)
script o
Line 582 ⟶ 583:
 
{{output}}
<syntaxhighlight lang="applescript">{|numbers|:{28.0, 75.6, 21.4, 51.8, 79.6, 25.0, 95.4, 31.2}, median:41.5}</syntaxhighlight>
 
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang=Applesoft"applesoft BASICbasic"> 100 REMMEDIAN
110 K = INT(L/2) : GOSUB 150
120 R = X(K)
Line 609 ⟶ 610:
300 REMSWAP
310 H = X(P1):X(P1) = X(P2)
320 X(P2) = H: RETURN</syntaxhighlight>Example:<syntaxhighlight lang=ApplesoftBASIC"applesoftbasic">X(0)=4.4 : X(1)=2.3 : X(2)=-1.7 : X(3)=7.5 : X(4)=6.6 : X(5)=0.0 : X(6)=1.9 : X(7)=8.2 : X(8)=9.3 : X(9)=4.5 : X(10)=-11.7
L = 11 : GOSUB 100MEDIAN
? R</syntaxhighlight>Output:<pre>5.95</pre>
Line 615 ⟶ 616:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">arr: [1 2 3 4 5 6 7]
arr2: [1 2 3 4 5 6]
Line 628 ⟶ 629:
=={{header|AutoHotkey}}==
Takes the lower of the middle two if length is even
<syntaxhighlight lang=AutoHotkey"autohotkey">seq = 4.1, 7.2, 1.7, 9.3, 4.4, 3.2, 5
MsgBox % median(seq, "`,") ; 4.1
 
Line 643 ⟶ 644:
AWK arrays can be passed as parameters, but not returned, so they are usually global.
 
<syntaxhighlight lang="awk">#!/usr/bin/awk -f
 
BEGIN {
Line 697 ⟶ 698:
 
=={{header|BaCon}}==
<syntaxhighlight lang="freebasic">DECLARE a[] = { 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING
DECLARE b[] = { 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING
 
Line 726 ⟶ 727:
Note that in order to truly work with the Windows versions of PowerBASIC, the module-level code must be contained inside <code>FUNCTION PBMAIN</code>. Similarly, in order to work under Visual Basic, the same module-level code must be contained with <code>Sub Main</code>.
 
<syntaxhighlight lang="qbasic">DECLARE FUNCTION median! (vector() AS SINGLE)
 
DIM vec1(10) AS SINGLE, vec2(11) AS SINGLE, n AS INTEGER
Line 761 ⟶ 762:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
 
Line 794 ⟶ 795:
Each number is packaged in a little list and these lists are accumulated in a sum. Bracmat keeps sums sorted, so the median is the term in the middle of the list, or the average of the two terms in the middle of the list.
 
<syntaxhighlight lang="bracmat">(median=
begin decimals end int list med med1 med2 num number
. 0:?list
Line 834 ⟶ 835:
 
=={{header|C}}==
<syntaxhighlight lang=C"c">#include <stdio.h>
#include <stdlib.h>
 
Line 867 ⟶ 868:
===Quickselect algorithm===
Average O(n) time:
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Line 949 ⟶ 950:
 
Output:
<syntaxhighlight lang="c">length: 992021
median: 0.000473
<: 496010
Line 956 ⟶ 957:
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 993 ⟶ 994:
=={{header|C++}}==
This function runs in linear time on average.
<syntaxhighlight lang="cpp">#include <algorithm>
 
// inputs must be random-access iterators of doubles
Line 1,029 ⟶ 1,030:
Uses a GNU C++ policy-based data structure to compute median in O(log n) time.
{{libheader|gnu_pbds}}
<syntaxhighlight lang="cpp">#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
Line 1,072 ⟶ 1,073:
=={{header|Clojure}}==
Simple:
<syntaxhighlight lang="lisp">(defn median [ns]
(let [ns (sort ns)
cnt (count ns)
Line 1,082 ⟶ 1,083:
=={{header|COBOL}}==
Intrinsic function:
<syntaxhighlight lang="cobol">FUNCTION MEDIAN(some-table (ALL))</syntaxhighlight>
 
=={{header|Common Lisp}}==
Line 1,088 ⟶ 1,089:
The recursive partitioning solution, without the median of medians optimization.
 
<syntaxhighlight lang="lisp">((defun select-nth (n list predicate)
"Select nth element in list, ordered by predicate, modifying list."
(do ((pivot (pop list))
Line 1,113 ⟶ 1,114:
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">def median(ary)
srtd = ary.sort
alen = srtd.size
Line 1,137 ⟶ 1,138:
 
=={{header|D}}==
<syntaxhighlight lang="d">import std.stdio, std.algorithm;
 
T median(T)(T[] nums) pure nothrow {
Line 1,159 ⟶ 1,160:
 
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi"delphi">program AveragesMedian;
 
{$APPTYPE CONSOLE}
Line 1,185 ⟶ 1,186:
=={{header|E}}==
 
TODO: Use the selection algorithm, whatever that is [[Category:E examples needing attention]]
<syntaxhighlight lang="e">def median(list) {
 
<syntaxhighlight lang=e>def median(list) {
def sorted := list.sort()
def count := sorted.size()
Line 1,199:
}</syntaxhighlight>
 
<syntaxhighlight lang="e">? median([1,9,2])
# value: 2
 
Line 1,207:
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">func quickselect k . list[] res .
#
subr partition
Line 1,255:
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(define (median L) ;; O(n log(n))
(set! L (vector-sort! < (list->vector L)))
Line 1,275:
=={{header|Elena}}==
ELENA 5.0 :
<syntaxhighlight lang="elena">import system'routines;
import system'math;
import extensions;
Line 1,323:
=={{header|Elixir}}==
{{trans|Erlang}}
<syntaxhighlight lang="elixir">defmodule Average do
def median([]), do: nil
def median(list) do
Line 1,352:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">-module(median).
-import(lists, [nth/2, sort/1]).
-compile(export_all).
Line 1,418:
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM MEDIAN
 
Line 1,464:
v. Moreover it can search for the p median, not only the p=0.5 median.
 
<syntaxhighlight lang=Euler"euler Mathmath Toolboxtoolbox">
>type median
function median (x, v: none, p)
Line 1,518:
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">function median(sequence s)
atom min,k
-- Selection sort of half+1
Line 1,551:
Assuming the values are entered in the A column, type into any cell which will not be part of the list :
 
<syntaxhighlight lang="excel">
=MEDIAN(A1:A10)
</syntaxhighlight>
Line 1,557:
Assuming 10 values will be entered, alternatively, you can just type
 
<syntaxhighlight lang="excel">
=MEDIAN(
</syntaxhighlight>
Line 1,564:
The output for the first expression, for any 10 numbers is
 
<syntaxhighlight lang="text">
23 11,5
21
Line 1,579:
=={{header|F Sharp|F#}}==
Median of Medians algorithm implementation
<syntaxhighlight lang="fsharp">
let rec splitToFives list =
match list with
Line 1,628:
=={{header|Factor}}==
The quicksort-style solution, with random pivoting. Takes the lesser of the two medians for even sequences.
<syntaxhighlight lang="factor">USING: arrays kernel locals math math.functions random sequences ;
IN: median
 
Line 1,657:
 
Usage:
<syntaxhighlight lang="factor">( scratchpad ) 11 iota median .
5
( scratchpad ) 10 iota median .
Line 1,664:
=={{header|Forth}}==
This uses the O(n) algorithm derived from [[quicksort]].
<syntaxhighlight lang="forth">-1 cells constant -cell
: cell- -cell + ;
 
Line 1,694:
1- cells over + 2dup mid to midpoint
select midpoint @ ;</syntaxhighlight>
<syntaxhighlight lang="forth">create test 4 , 2 , 1 , 3 , 5 ,
 
test 4 median . \ 2
Line 1,702:
{{works with|Fortran|90 and later}}
 
<syntaxhighlight lang="fortran">program Median_Test
 
real :: a(7) = (/ 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 /), &
Line 1,746:
end program Median_Test</syntaxhighlight>
 
If one refers to [[Quickselect_algorithm#Fortran]] which offers function FINDELEMENT(K,A,N) that returns the value of A(K) when the array of N elements has been rearranged if necessary so that A(K) is the K'th in order, then, supposing that a version is devised using the appropriate type for array A, <syntaxhighlight lang=Fortran"fortran"> K = N/2
MEDIAN = FINDELEMENT(K + 1,A,N)
IF (MOD(N,2).EQ.0) MEDIAN = (FINDELEMENT(K,A,N) + MEDIAN)/2 </syntaxhighlight>
Line 1,752:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub quicksort(a() As Double, first As Integer, last As Integer)
Line 1,806:
 
=={{header|GAP}}==
<syntaxhighlight lang="gap">Median := function(v)
local n, w;
w := SortedList(v);
Line 1,824:
===Sort===
Go built-in sort. O(n log n).
<syntaxhighlight lang="go">package main
 
import (
Line 1,850:
Unfortunately in the case of median, k is n/2 so the algorithm is O(n^2). Still, it gives the idea of median by selection. Note that the partial selection sort does leave the k smallest values sorted, so in the case of an even number of elements, the two elements to average are available after a single call to sel().
 
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 1,883:
===Quickselect===
It doesn't take too much more code to implement a quickselect with random pivoting, which should run in expected time O(n). The qsel function here permutes elements of its parameter "a" in place. It leaves the slice somewhat more ordered, but unlike the sort and partial sort examples above, does not guarantee that element k-1 is in place. For the case of an even number of elements then, median must make two separate qsel() calls.
<syntaxhighlight lang="go">package main
 
import (
Line 1,938:
=={{header|Groovy}}==
Solution (brute force sorting, with arithmetic averaging of dual midpoints (even sizes)):
<syntaxhighlight lang="groovy">def median(Iterable col) {
def s = col as SortedSet
if (s == null) return null
Line 1,949:
 
Test:
<syntaxhighlight lang="groovy">def a = [4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5]
def sz = a.size()
 
Line 1,984:
 
This uses a quick select algorithm and runs in expected O(n) time.
<syntaxhighlight lang="haskell">import Data.List (partition)
 
nth :: Ord t => [t] -> Int -> t
Line 2,019:
Or {{libheader|hstats}}
 
<syntaxhighlight lang="haskell">> Math.Statistics.median [1,9,2,4]
3.0</syntaxhighlight>
 
=={{header|HicEst}}==
If the input has an even number of elements, median is the mean of the middle two values:
<syntaxhighlight lang=HicEst"hicest">REAL :: n=10, vec(n)
 
vec = RAN(1)
Line 2,037:
=={{header|Icon}} and {{header|Unicon}}==
A quick and dirty solution:
<syntaxhighlight lang="text">procedure main(args)
write(median(args))
end
Line 2,057:
=={{header|J}}==
The verb <code>median</code> is available from the <code>stats/base</code> addon and returns the mean of the two middle values for an even number of elements:
<syntaxhighlight lang="j"> require 'stats/base'
median 1 9 2 4
3</syntaxhighlight>
The definition given in the addon script is:
<syntaxhighlight lang="j">midpt=: -:@<:@#
median=: -:@(+/)@((<. , >.)@midpt { /:~)</syntaxhighlight>
 
If, for an even number of elements, both values were desired when those two values are distinct, then the following implementation would suffice:
<syntaxhighlight lang="j"> median=: ~.@(<. , >.)@midpt { /:~
median 1 9 2 4
2 4</syntaxhighlight>
Line 2,073:
 
Sorting:
<syntaxhighlight lang="java5">// Note: this function modifies the input list
public static double median(List<Double> list) {
Collections.sort(list);
Line 2,082:
 
Using priority queue (which sorts under the hood):
<syntaxhighlight lang="java5">public static double median2(List<Double> list) {
PriorityQueue<Double> pq = new PriorityQueue<Double>(list);
int n = list.size();
Line 2,097:
This version operates on objects rather than primitives and uses abstractions to operate on all of the standard numerics.
 
<syntaxhighlight lang="java8">
@FunctionalInterface
interface MedianFinder<T, R> extends Function<Collection<T>, R> {
Line 2,153:
 
===ES5===
<syntaxhighlight lang="javascript">function median(ary) {
if (ary.length == 0)
return null;
Line 2,174:
{{Trans|Haskell}}
 
<syntaxhighlight lang=JavaScript"javascript">(() => {
'use strict';
 
Line 2,228:
 
{{Out}}
<syntaxhighlight lang=JavaScript"javascript">[
null,
4,
Line 2,236:
 
=={{header|jq}}==
<syntaxhighlight lang="jq">def median:
length as $length
| sort as $s
Line 2,245:
else $s[$l2]
end
end ;</syntaxhighlight>This definition can be used in a jq program, but to illustrate how it can be used as a command line filter, suppose the definition and the program '''median''' are in a file named median.jq, and that the file in.dat contains a sequence of arrays, such as <syntaxhighlight lang="sh">[4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]
[4.1, 7.2, 1.7, 9.3, 4.4, 3.2]</syntaxhighlight>Then invoking the jq program yields a stream of values:<syntaxhighlight lang="sh">$ jq -f median.jq in.dat
4.4
4.25</syntaxhighlight>
Line 2,252:
=={{header|Julia}}==
Julia has a built-in median() function
<syntaxhighlight lang="julia">using Statistics
function median2(n)
s = sort(n)
Line 2,279:
 
=={{header|K}}==
<syntaxhighlight lang="k">
med:{a:x@<x; i:(#a)%2; :[(#a)!2; a@i; {(+/x)%#x} a@i,i-1]}
v:10*6 _draw 0
Line 2,291:
 
An alternate solution which works in the oK implementation using the same dataset v from above and shows both numbers around the median point on even length datasets would be:
<syntaxhighlight lang="k">
med:{a:x@<x; i:_(#a)%2
$[2!#a; a@i; |a@i,i-1]}
Line 2,300:
=={{header|Kotlin}}==
{{works with|Kotlin|1.0+}}
<syntaxhighlight lang="scala">fun median(l: List<Double>) = l.sorted().let { (it[it.size / 2] + it[(it.size - 1) / 2]) / 2 }
 
fun main(args: Array<String>) {
Line 2,313:
 
Lasso's built in function is "median( value_1, value_2, value_3 )"
<syntaxhighlight lang=Lasso"lasso">define median_ext(a::array) => {
#a->sort
 
Line 2,330:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
dim a( 100), b( 100) ' assumes we will not have vectors of more terms...
 
Line 2,397:
 
=={{header|Lingo}}==
<syntaxhighlight lang=Lingo"lingo">on median (numlist)
-- numlist = numlist.duplicate() -- if input list should not be altered
numlist.sort()
Line 2,409:
=={{header|LiveCode}}==
LC has median as a built-in function
<syntaxhighlight lang=LiveCode"livecode">put median("4.1,5.6,7.2,1.7,9.3,4.4,3.2") & "," & median("4.1,7.2,1.7,9.3,4.4,3.2")
returns 4.4, 4.25</syntaxhighlight>
 
To make our own, we need own own floor function first
 
<syntaxhighlight lang=LiveCode"livecode">function floor n
if n < 0 then
return (trunc(n) - 1)
Line 2,440:
 
=={{header|LSL}}==
<syntaxhighlight lang=LSL"lsl">integer MAX_ELEMENTS = 10;
integer MAX_VALUE = 100;
default {
Line 2,478:
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">function median (numlist)
if type(numlist) ~= 'table' then return numlist end
table.sort(numlist)
Line 2,491:
=== Builtin ===
This works for numeric lists or arrays, and is designed for large data sets.
<syntaxhighlight lang=Maple"maple">
> Statistics:-Median( [ 1, 5, 3, 2, 4 ] );
3.
Line 2,500:
=== Using a sort ===
This solution can handle exact numeric inputs. Instead of inputting a container of some kind, it simply finds the median of its arguments.
<syntaxhighlight lang=Maple"maple">
median1 := proc()
local L := sort( [ args ] );
Line 2,507:
</syntaxhighlight>
For example:
<syntaxhighlight lang=Maple"maple">
> median1( 1, 5, 3, 2, 4 ); # 3
3
Line 2,517:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Built-in function:
<syntaxhighlight lang=Mathematica"mathematica">Median[{1, 5, 3, 2, 4}]
Median[{1, 5, 3, 6, 4, 2}]</syntaxhighlight>
{{out}}
Line 2,523:
7/2</pre>
Custom function:
<syntaxhighlight lang=Mathematica"mathematica">mymedian[x_List]:=Module[{t=Sort[x],L=Length[x]},
If[Mod[L,2]==0,
(t[[L/2]]+t[[L/2+1]])/2
Line 2,531:
]</syntaxhighlight>
Example of custom function:
<syntaxhighlight lang=Mathematica"mathematica">mymedian[{1, 5, 3, 2, 4}]
mymedian[{1, 5, 3, 6, 4, 2}]</syntaxhighlight>
{{out}}
Line 2,539:
=={{header|MATLAB}}==
If the input has an even number of elements, function returns the mean of the middle two values:
<syntaxhighlight lang=Matlab"matlab">function medianValue = findmedian(setOfValues)
medianValue = median(setOfValues);
end</syntaxhighlight>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">/* built-in */
median([41, 56, 72, 17, 93, 44, 32]); /* 44 */
median([41, 72, 17, 93, 44, 32]); /* 85/2 */</syntaxhighlight>
 
=={{header|MiniScript}}==
<syntaxhighlight lang=MiniScript"miniscript">list.median = function()
self.sort
m = floor(self.len/2)
Line 2,563:
 
=={{header|MUMPS}}==
<syntaxhighlight lang=MUMPS"mumps">MEDIAN(X)
;X is assumed to be a list of numbers separated by "^"
;I is a loop index
Line 2,589:
=={{header|Nanoquery}}==
{{trans|Python}}
<syntaxhighlight lang=Nanoquery"nanoquery">import sort
 
def median(aray)
Line 2,604:
=={{header|NetRexx}}==
{{trans|Java}}
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,692:
 
=={{header|NewLISP}}==
<syntaxhighlight lang=NewLISP"newlisp">; median.lsp
; oofoe 2012-01-25
 
Line 2,726:
=={{header|Nim}}==
{{trans|Python}}
<syntaxhighlight lang="nim">import algorithm, strutils
proc median(xs: seq[float]): float =
Line 2,744:
=={{header|Oberon-2}}==
Oxford Oberon-2
<syntaxhighlight lang="oberon2">
MODULE Median;
IMPORT Out;
Line 2,836:
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
use Structure;
 
Line 2,871:
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">(* note: this modifies the input array *)
let median array =
let len = Array.length array in
Line 2,884:
=={{header|Octave}}==
Of course Octave has its own <tt>median</tt> function we can use to check our implementation. The Octave's median function, however, does not handle the case you pass in a void vector.
<syntaxhighlight lang="octave">function y = median2(v)
if (numel(v) < 1)
y = NA;
Line 2,907:
 
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx"oorexx">
call testMedian .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testMedian .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
Line 2,947:
 
=={{header|Oz}}==
<syntaxhighlight lang="oz">declare
fun {Median Xs}
Len = {Length Xs}
Line 2,963:
=={{header|PARI/GP}}==
Sorting solution.
<syntaxhighlight lang="parigp">median(v)={
vecsort(v)[#v\2]
};</syntaxhighlight>
 
Linear-time solution, mostly proof-of-concept but perhaps suitable for large lists.
<syntaxhighlight lang="parigp">BFPRT(v,k=#v\2)={
if(#v<15, return(vecsort(v)[k]));
my(u=List(),pivot,left=List(),right=List());
Line 2,992:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<syntaxhighlight lang="pascal">Program AveragesMedian(output);
 
type
Line 3,059:
=={{header|Perl}}==
{{trans|Python}}
<syntaxhighlight lang="perl">sub median {
my @a = sort {$a <=> $b} @_;
return ($a[$#a/2] + $a[@a/2]) / 2;
Line 3,066:
=={{header|Phix}}==
The obvious simple way:
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">median</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 3,083:
It is also possible to use the [[Quickselect_algorithm#Phix|quick_select]] routine for a small (20%) performance improvement,
which as suggested below may with luck be magnified by retaining any partially sorted results.
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">medianq</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 3,100:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">include ..\Utilitys.pmt
 
def median /# l -- n #/
Line 3,117:
=={{header|PHP}}==
This solution uses the sorting method of finding the median.
<syntaxhighlight lang="php">
function median($arr)
{
Line 3,138:
 
=={{header|Picat}}==
<syntaxhighlight lang=Picat"picat">go =>
Lists = [
[1.121,10.3223,3.41,12.1,0.01],
Line 3,177:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de median (Lst)
(let N (length Lst)
(if (bit? 1 N)
Line 3,196:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">call sort(A);
n = dimension(A,1);
if iand(n,1) = 1 then /* an odd number of elements */
Line 3,208:
All statistical properties could easily be added to the output object.
 
<syntaxhighlight lang=PowerShell"powershell">
function Measure-Data
{
Line 3,279:
}
</syntaxhighlight>
<syntaxhighlight lang=PowerShell"powershell">
$statistics = Measure-Data 4, 5, 6, 7, 7, 7, 8, 1, 1, 1, 2, 3
$statistics
Line 3,296:
</pre>
Median only:
<syntaxhighlight lang=PowerShell"powershell">
$statistics.Median
</syntaxhighlight>
Line 3,305:
 
=={{header|Processing}}==
<syntaxhighlight lang=Processing"processing">void setup() {
float[] numbers = {3.1, 4.1, 5.9, 2.6, 5.3, 5.8};
println(median(numbers));
Line 3,322:
 
=={{header|Prolog}}==
<syntaxhighlight lang=Prolog"prolog">median(L, Z) :-
length(L, Length),
I is Length div 2,
Line 3,334:
=={{header|Pure}}==
Inspired by the Haskell version.
<syntaxhighlight lang=Pure"pure">median x = (/(2-rem)) $ foldl1 (+) $ take (2-rem) $ drop (mid-(1-rem)) $ sort (<=) x
when len = # x;
mid = len div 2;
Line 3,346:
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Procedure.d median(Array values.d(1), length.i)
If length = 0 : ProcedureReturn 0.0 : EndIf
SortArray(values(), #PB_Sort_Ascending)
Line 3,383:
 
=={{header|Python}}==
<syntaxhighlight lang="python">def median(aray):
srtd = sorted(aray)
alen = len(srtd)
Line 3,397:
{{trans|Octave}}
 
<syntaxhighlight lang="rsplus">omedian <- function(v) {
if ( length(v) < 1 )
NA
Line 3,419:
 
=={{header|Racket}}==
<syntaxhighlight lang=Racket"racket">#lang racket
(define (median numbers)
(define sorted (list->vector (sort (vector->list numbers) <)))
Line 3,438:
 
{{works with|Rakudo|2016.08}}
<syntaxhighlight lang=perl6"raku" line>sub median {
my @a = sort @_;
return (@a[(*-1) div 2] + @a[* div 2]) / 2;
Line 3,450:
<br>
In a slightly more compact way:
<syntaxhighlight lang=perl6"raku" line>sub median { @_.sort[(*-1)/2, */2].sum / 2 }</syntaxhighlight>
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">
median: func [
"Returns the midpoint value in a series of numbers; half the values are above, half are below."
Line 3,472:
 
=={{header|ReScript}}==
<syntaxhighlight lang=ReScript"rescript">let median = (arr) =>
{
let float_compare = (a, b) => {
Line 3,505:
 
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/*REXX program finds the median of a vector (and displays the vector and median).*/
/* ══════════vector════════════ ══show vector═══ ════════show result═══════════ */
v= 1 9 2 4 ; say "vector" v; say 'median──────►' median(v); say
Line 3,545:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
aList = [5,4,2,3]
see "medium : " + median(aList) + nl
Line 3,558:
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">def median(ary)
return nil if ary.empty?
mid, rem = ary.length.divmod(2)
Line 3,574:
 
Alternately:
<syntaxhighlight lang="ruby">def median(aray)
srtd = aray.sort
alen = srtd.length
Line 3,581:
 
=={{header|Run BASIC}}==
<syntaxhighlight lang=Runbasic"runbasic">sqliteconnect #mem, ":memory:"
mem$ = "CREATE TABLE med (x float)"
#mem execute(mem$)
Line 3,622:
Sorting, then obtaining the median element:
 
<syntaxhighlight lang="rust">fn median(mut xs: Vec<f64>) -> f64 {
// sort in ascending order, panic on f64::NaN
xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );
Line 3,644:
{{works with|Scala|2.8}} (See the Scala discussion on [[Mean]] for more information.)
 
<syntaxhighlight lang="scala">def median[T](s: Seq[T])(implicit n: Fractional[T]) = {
import n._
val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2)
Line 3,657:
{{trans|Python}}
Using Rosetta Code's [[Bubble_Sort#Scheme|bubble-sort function]]
<syntaxhighlight lang=Scheme"scheme">(define (median l)
(* (+ (list-ref (bubble-sort l >) (round (/ (- (length l) 1) 2)))
(list-ref (bubble-sort l >) (round (/ (length l) 2)))) 0.5))</syntaxhighlight>
 
Using [http://srfi.schemers.org/srfi-95/srfi-95.html SRFI-95]:
<syntaxhighlight lang=Scheme"scheme">(define (median l)
(* (+ (list-ref (sort l less?) (round (/ (- (length l) 1) 2)))
(list-ref (sort l less?) (round (/ (length l) 2)))) 0.5))</syntaxhighlight>
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
Line 3,698:
=={{header|SenseTalk}}==
SenseTalk has a built-in median function. This example also shows the implementation of a customMedian function that returns the same results.
<syntaxhighlight lang="sensetalk">put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]
put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]
 
Line 3,714:
end customMedian</syntaxhighlight>
Output:
<syntaxhighlight lang="sensetalk">4.4
5
4.4
Line 3,720:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func median(arry) {
var srtd = arry.sort;
var alen = srtd.length;
Line 3,727:
 
=={{header|Slate}}==
<syntaxhighlight lang="slate">s@(Sequence traits) median
[
s isEmpty
Line 3,739:
].</syntaxhighlight>
 
<syntaxhighlight lang="slate">inform: { 4.1 . 5.6 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } median.
inform: { 4.1 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } median.</syntaxhighlight>
 
Line 3,745:
{{works with|GNU Smalltalk}}
 
<syntaxhighlight lang="smalltalk">OrderedCollection extend [
median [
self size = 0
Line 3,759:
].</syntaxhighlight>
 
<syntaxhighlight lang="smalltalk">{ 4.1 . 5.6 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } asOrderedCollection
median displayNl.
{ 4.1 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } asOrderedCollection
Line 3,767:
Use '''[https://www.stata.com/help.cgi?summarize summarize]''' to compute the median of a variable (as well as other basic statistics).
 
<syntaxhighlight lang="stata">set obs 100000
gen x=rbeta(0.2,1.3)
quietly summarize x, detail
Line 3,774:
Here is a straightforward implementation using '''[https://www.stata.com/help.cgi? sort]'''.
 
<syntaxhighlight lang="stata">program calcmedian, rclass sortpreserve
sort `1'
if mod(_N,2)==0 {
Line 3,788:
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">proc median args {
set list [lsort -real $args]
set len [llength $list]
Line 3,808:
 
Using the built-in function:
<syntaxhighlight lang="ti83b">median({1.1, 2.5, 0.3241})</syntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
<syntaxhighlight lang="ti89b">median({3, 4, 1, -8.4, 7.2, 4, 1, 1})</syntaxhighlight>
 
=={{header|Ursala}}==
the simple way (sort first and then look in the middle)
<syntaxhighlight lang=Ursala"ursala">#import std
#import flo
 
median = fleq-<; @K30K31X eql?\~&rh div\2.+ plus@lzPrhPX</syntaxhighlight>
test program, once with an odd length and once with an even length vector
<syntaxhighlight lang=Ursala"ursala">#cast %eW
 
examples =
Line 3,835:
Requires <code>--pkg posix -X -lm</code> compilation flags in order to use POSIX qsort, and to have access to math library.
 
<syntaxhighlight lang="vala">int compare_numbers(void* a_ref, void* b_ref) {
double a = *(double*) a_ref;
double b = *(double*) b_ref;
Line 3,858:
{{trans|Phix}}
Uses [[Quickselect_algorithm#VBA|quick select]].
<syntaxhighlight lang="vb">Private Function medianq(s As Variant) As Double
Dim res As Double, tmp As Integer
Dim l As Integer, k As Integer
Line 3,884:
The result is returned in text register @10. In case of even number of items, the lower middle value is returned.
 
<syntaxhighlight lang="vedit">Sort(0, File_Size, NOCOLLATE+NORESTORE)
EOF Goto_Line(Cur_Line/2)
Reg_Copy(10, 1)</syntaxhighlight>
 
=={{header|Vlang}}==
<syntaxhighlight lang="vlang">fn main() {
println(median([3, 1, 4, 1])) // prints 2
println(median([3, 1, 4, 1, 5])) // prints 3
Line 3,911:
</pre>
If you use math.stats module the list parameter must be sorted
<syntaxhighlight lang="text">import math.stats
fn main() {
println(stats.median<int>([1, 1, 3, 4])) // prints 2
Line 3,918:
 
=={{header|Wortel}}==
<syntaxhighlight lang="wortel">@let {
; iterative
med1 &l @let {a @sort l s #a i @/s 2 ?{%%s 2 ~/ 2 +`-i 1 a `i a `i a}}
Line 3,938:
{{libheader|Wren-math}}
{{libheader|Wren-queue}}
<syntaxhighlight lang="ecmascript">import "/sort" for Sort, Find
import "/math" for Nums
import "/queue" for PriorityQueue
Line 3,984:
=={{header|Yabasic}}==
{{trans|Lua}}
<syntaxhighlight lang=Yabasic"yabasic">sub floor(x)
return int(x + .05)
end sub
Line 4,044:
=={{header|zkl}}==
Using the [[Quickselect algorithm#zkl]] for O(n) time:
<syntaxhighlight lang="zkl">var quickSelect=Import("quickSelect").qselect;
 
fcn median(xs){
Line 4,051:
( quickSelect(xs,n/2-1) + quickSelect(xs,n/2) )/2;
}</syntaxhighlight>
<syntaxhighlight lang="zkl">median(T( 5.1, 2.6, 6.2, 8.8, 4.6, 4.1 )); //-->4.85
median(T( 5.1, 2.6, 8.8, 4.6, 4.1 )); //-->4.6</syntaxhighlight>
 
=={{header|Zoea}}==
<syntaxhighlight lang=Zoea"zoea">
program: median
case: 1
Line 4,072:
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
module Averages;
 
10,333

edits