Averages/Median: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
{{task|Probability and statistics}}
[[Category:Sorting]]
[[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.
Write a program to find the   [[wp:Median|median]]   value of a vector of floating-point numbers.
Line 20: Line 21:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang=11l>F median(aray)
<syntaxhighlight lang="11l">F median(aray)
V srtd = sorted(aray)
V srtd = sorted(aray)
V alen = srtd.len
V alen = srtd.len
Line 36: Line 37:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang=Action!>INCLUDE "H6:REALMATH.ACT"
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"


DEFINE PTR="CARD"
DEFINE PTR="CARD"
Line 118: Line 119:


=={{header|Ada}}==
=={{header|Ada}}==
<syntaxhighlight lang=ada>with Ada.Text_IO, Ada.Float_Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Float_Text_IO;


procedure FindMedian is
procedure FindMedian is
Line 151: Line 152:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{trans|C}}<syntaxhighlight lang=algol68>INT max_elements = 1000000;
{{trans|C}}<syntaxhighlight lang="algol68">INT max_elements = 1000000;
# Return the k-th smallest item in array x of length len #
# Return the k-th smallest item in array x of length len #
Line 226: Line 227:
=={{header|AntLang}}==
=={{header|AntLang}}==
AntLang has a built-in median function.
AntLang has a built-in median function.
<syntaxhighlight lang=AntLang>median[list]</syntaxhighlight>
<syntaxhighlight lang="antlang">median[list]</syntaxhighlight>


=={{header|APL}}==
=={{header|APL}}==
<syntaxhighlight lang=APL>median←{v←⍵[⍋⍵]⋄.5×v[⌈¯1+.5×⍴v]+v[⌊.5×⍴v]} ⍝ Assumes ⎕IO←0</syntaxhighlight>
<syntaxhighlight lang="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.
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>⎕IO←0</syntaxhighlight>
Note that the index origin ⎕IO is assumed zero. To set it to zero use: <syntaxhighlight lang="apl">⎕IO←0</syntaxhighlight>


If you prefer an index origin of 1, use this code instead:
If you prefer an index origin of 1, use this code instead:
<syntaxhighlight lang=APL>
<syntaxhighlight lang="apl">
⎕IO←1
⎕IO←1
median←{v←⍵[⍋⍵] ⋄ 0.5×v[⌈0.5×⍴v]+v[⌊1+0.5×⍴v]}
median←{v←⍵[⍋⍵] ⋄ 0.5×v[⌈0.5×⍴v]+v[⌊1+0.5×⍴v]}
Line 276: Line 277:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
===By iteration===
===By iteration===
<syntaxhighlight lang=applescript>set alist to {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}
<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)
set med to medi(alist)


Line 322: Line 323:


{{output}}
{{output}}
<syntaxhighlight lang=applescript>4.5</syntaxhighlight>
<syntaxhighlight lang="applescript">4.5</syntaxhighlight>


===Composing functionally===
===Composing functionally===
Line 328: Line 329:
{{Trans|JavaScript}}
{{Trans|JavaScript}}
{{Trans|Haskell}}
{{Trans|Haskell}}
<syntaxhighlight lang=AppleScript>-- MEDIAN ---------------------------------------------------------------------
<syntaxhighlight lang="applescript">-- MEDIAN ---------------------------------------------------------------------


-- median :: [Num] -> Num
-- median :: [Num] -> Num
Line 435: Line 436:
end uncons</syntaxhighlight>
end uncons</syntaxhighlight>
{{Out}}
{{Out}}
<syntaxhighlight lang=AppleScript>{missing value, 4, 3.5, 2.1}</syntaxhighlight>
<syntaxhighlight lang="applescript">{missing value, 4, 3.5, 2.1}</syntaxhighlight>


----
----


===Quickselect===
===Quickselect===
<syntaxhighlight lang=applescript>-- Return the median value of items l thru r of a list of numbers.
<syntaxhighlight lang="applescript">-- Return the median value of items l thru r of a list of numbers.
on getMedian(theList, l, r)
on getMedian(theList, l, r)
if (theList is {}) then return theList
if (theList is {}) then return theList
Line 517: Line 518:
<pre>{|numbers|:{71.6, 44.8, 45.8, 28.6, 96.8, 98.4, 42.4, 97.8}, median:58.7}</pre>
<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===
===Partial heap sort===
<syntaxhighlight lang=applescript>-- Based on the heap sort algorithm ny J.W.J. Williams.
<syntaxhighlight lang="applescript">-- Based on the heap sort algorithm ny J.W.J. Williams.
on getMedian(theList, l, r)
on getMedian(theList, l, r)
script o
script o
Line 582: Line 583:


{{output}}
{{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>
<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}}==
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang=Applesoft BASIC> 100 REMMEDIAN
<syntaxhighlight lang="applesoft basic"> 100 REMMEDIAN
110 K = INT(L/2) : GOSUB 150
110 K = INT(L/2) : GOSUB 150
120 R = X(K)
120 R = X(K)
Line 609: Line 610:
300 REMSWAP
300 REMSWAP
310 H = X(P1):X(P1) = X(P2)
310 H = X(P1):X(P1) = X(P2)
320 X(P2) = H: RETURN</syntaxhighlight>Example:<syntaxhighlight lang=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
320 X(P2) = H: RETURN</syntaxhighlight>Example:<syntaxhighlight lang="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
L = 11 : GOSUB 100MEDIAN
? R</syntaxhighlight>Output:<pre>5.95</pre>
? R</syntaxhighlight>Output:<pre>5.95</pre>
Line 615: Line 616:
=={{header|Arturo}}==
=={{header|Arturo}}==


<syntaxhighlight lang=rebol>arr: [1 2 3 4 5 6 7]
<syntaxhighlight lang="rebol">arr: [1 2 3 4 5 6 7]
arr2: [1 2 3 4 5 6]
arr2: [1 2 3 4 5 6]
Line 628: Line 629:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Takes the lower of the middle two if length is even
Takes the lower of the middle two if length is even
<syntaxhighlight lang=AutoHotkey>seq = 4.1, 7.2, 1.7, 9.3, 4.4, 3.2, 5
<syntaxhighlight lang="autohotkey">seq = 4.1, 7.2, 1.7, 9.3, 4.4, 3.2, 5
MsgBox % median(seq, "`,") ; 4.1
MsgBox % median(seq, "`,") ; 4.1


Line 643: Line 644:
AWK arrays can be passed as parameters, but not returned, so they are usually global.
AWK arrays can be passed as parameters, but not returned, so they are usually global.


<syntaxhighlight lang=awk>#!/usr/bin/awk -f
<syntaxhighlight lang="awk">#!/usr/bin/awk -f


BEGIN {
BEGIN {
Line 697: Line 698:


=={{header|BaCon}}==
=={{header|BaCon}}==
<syntaxhighlight lang=freebasic>DECLARE a[] = { 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING
<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
DECLARE b[] = { 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING


Line 726: Line 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>.
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)
<syntaxhighlight lang="qbasic">DECLARE FUNCTION median! (vector() AS SINGLE)


DIM vec1(10) AS SINGLE, vec2(11) AS SINGLE, n AS INTEGER
DIM vec1(10) AS SINGLE, vec2(11) AS SINGLE, n AS INTEGER
Line 761: Line 762:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang=bbcbasic> INSTALL @lib$+"SORTLIB"
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
Sort% = FN_sortinit(0,0)


Line 794: Line 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.
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=
<syntaxhighlight lang="bracmat">(median=
begin decimals end int list med med1 med2 num number
begin decimals end int list med med1 med2 num number
. 0:?list
. 0:?list
Line 834: Line 835:


=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang=C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 867: Line 868:
===Quickselect algorithm===
===Quickselect algorithm===
Average O(n) time:
Average O(n) time:
<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <time.h>
#include <time.h>
Line 949: Line 950:


Output:
Output:
<syntaxhighlight lang=c>length: 992021
<syntaxhighlight lang="c">length: 992021
median: 0.000473
median: 0.000473
<: 496010
<: 496010
Line 956: Line 957:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;


Line 993: Line 994:
=={{header|C++}}==
=={{header|C++}}==
This function runs in linear time on average.
This function runs in linear time on average.
<syntaxhighlight lang=cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>


// inputs must be random-access iterators of doubles
// inputs must be random-access iterators of doubles
Line 1,029: Line 1,030:
Uses a GNU C++ policy-based data structure to compute median in O(log n) time.
Uses a GNU C++ policy-based data structure to compute median in O(log n) time.
{{libheader|gnu_pbds}}
{{libheader|gnu_pbds}}
<syntaxhighlight lang=cpp>#include <bits/stdc++.h>
<syntaxhighlight lang="cpp">#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/tree_policy.hpp>
Line 1,072: Line 1,073:
=={{header|Clojure}}==
=={{header|Clojure}}==
Simple:
Simple:
<syntaxhighlight lang=lisp>(defn median [ns]
<syntaxhighlight lang="lisp">(defn median [ns]
(let [ns (sort ns)
(let [ns (sort ns)
cnt (count ns)
cnt (count ns)
Line 1,082: Line 1,083:
=={{header|COBOL}}==
=={{header|COBOL}}==
Intrinsic function:
Intrinsic function:
<syntaxhighlight lang=cobol>FUNCTION MEDIAN(some-table (ALL))</syntaxhighlight>
<syntaxhighlight lang="cobol">FUNCTION MEDIAN(some-table (ALL))</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 1,088: Line 1,089:
The recursive partitioning solution, without the median of medians optimization.
The recursive partitioning solution, without the median of medians optimization.


<syntaxhighlight lang=lisp>((defun select-nth (n list predicate)
<syntaxhighlight lang="lisp">((defun select-nth (n list predicate)
"Select nth element in list, ordered by predicate, modifying list."
"Select nth element in list, ordered by predicate, modifying list."
(do ((pivot (pop list))
(do ((pivot (pop list))
Line 1,113: Line 1,114:


=={{header|Crystal}}==
=={{header|Crystal}}==
<syntaxhighlight lang=ruby>def median(ary)
<syntaxhighlight lang="ruby">def median(ary)
srtd = ary.sort
srtd = ary.sort
alen = srtd.size
alen = srtd.size
Line 1,137: Line 1,138:


=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>import std.stdio, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.algorithm;


T median(T)(T[] nums) pure nothrow {
T median(T)(T[] nums) pure nothrow {
Line 1,159: Line 1,160:


=={{header|Delphi}}==
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi>program AveragesMedian;
<syntaxhighlight lang="delphi">program AveragesMedian;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,185: Line 1,186:
=={{header|E}}==
=={{header|E}}==


TODO: Use the selection algorithm, whatever that is [[Category:E examples needing attention]]
TODO: Use the selection algorithm, whatever that is
<syntaxhighlight lang="e">def median(list) {

<syntaxhighlight lang=e>def median(list) {
def sorted := list.sort()
def sorted := list.sort()
def count := sorted.size()
def count := sorted.size()
Line 1,199: Line 1,199:
}</syntaxhighlight>
}</syntaxhighlight>


<syntaxhighlight lang=e>? median([1,9,2])
<syntaxhighlight lang="e">? median([1,9,2])
# value: 2
# value: 2


Line 1,207: Line 1,207:
=={{header|EasyLang}}==
=={{header|EasyLang}}==


<lang>func quickselect k . list[] res .
<syntaxhighlight lang="text">func quickselect k . list[] res .
#
#
subr partition
subr partition
Line 1,255: Line 1,255:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(define (median L) ;; O(n log(n))
(define (median L) ;; O(n log(n))
(set! L (vector-sort! < (list->vector L)))
(set! L (vector-sort! < (list->vector L)))
Line 1,275: Line 1,275:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<syntaxhighlight lang=elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import system'math;
import system'math;
import extensions;
import extensions;
Line 1,323: Line 1,323:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<syntaxhighlight lang=elixir>defmodule Average do
<syntaxhighlight lang="elixir">defmodule Average do
def median([]), do: nil
def median([]), do: nil
def median(list) do
def median(list) do
Line 1,352: Line 1,352:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang=erlang>-module(median).
<syntaxhighlight lang="erlang">-module(median).
-import(lists, [nth/2, sort/1]).
-import(lists, [nth/2, sort/1]).
-compile(export_all).
-compile(export_all).
Line 1,418: Line 1,418:


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang>
<syntaxhighlight lang="text">
PROGRAM MEDIAN
PROGRAM MEDIAN


Line 1,464: Line 1,464:
v. Moreover it can search for the p median, not only the p=0.5 median.
v. Moreover it can search for the p median, not only the p=0.5 median.


<syntaxhighlight lang=Euler Math Toolbox>
<syntaxhighlight lang="euler math toolbox">
>type median
>type median
function median (x, v: none, p)
function median (x, v: none, p)
Line 1,518: Line 1,518:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<syntaxhighlight lang=euphoria>function median(sequence s)
<syntaxhighlight lang="euphoria">function median(sequence s)
atom min,k
atom min,k
-- Selection sort of half+1
-- Selection sort of half+1
Line 1,551: Line 1,551:
Assuming the values are entered in the A column, type into any cell which will not be part of the list :
Assuming the values are entered in the A column, type into any cell which will not be part of the list :


<syntaxhighlight lang=excel>
<syntaxhighlight lang="excel">
=MEDIAN(A1:A10)
=MEDIAN(A1:A10)
</syntaxhighlight>
</syntaxhighlight>
Line 1,557: Line 1,557:
Assuming 10 values will be entered, alternatively, you can just type
Assuming 10 values will be entered, alternatively, you can just type


<syntaxhighlight lang=excel>
<syntaxhighlight lang="excel">
=MEDIAN(
=MEDIAN(
</syntaxhighlight>
</syntaxhighlight>
Line 1,564: Line 1,564:
The output for the first expression, for any 10 numbers is
The output for the first expression, for any 10 numbers is


<lang>
<syntaxhighlight lang="text">
23 11,5
23 11,5
21
21
Line 1,579: Line 1,579:
=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
Median of Medians algorithm implementation
Median of Medians algorithm implementation
<syntaxhighlight lang=fsharp>
<syntaxhighlight lang="fsharp">
let rec splitToFives list =
let rec splitToFives list =
match list with
match list with
Line 1,628: Line 1,628:
=={{header|Factor}}==
=={{header|Factor}}==
The quicksort-style solution, with random pivoting. Takes the lesser of the two medians for even sequences.
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 ;
<syntaxhighlight lang="factor">USING: arrays kernel locals math math.functions random sequences ;
IN: median
IN: median


Line 1,657: Line 1,657:


Usage:
Usage:
<syntaxhighlight lang=factor>( scratchpad ) 11 iota median .
<syntaxhighlight lang="factor">( scratchpad ) 11 iota median .
5
5
( scratchpad ) 10 iota median .
( scratchpad ) 10 iota median .
Line 1,664: Line 1,664:
=={{header|Forth}}==
=={{header|Forth}}==
This uses the O(n) algorithm derived from [[quicksort]].
This uses the O(n) algorithm derived from [[quicksort]].
<syntaxhighlight lang=forth>-1 cells constant -cell
<syntaxhighlight lang="forth">-1 cells constant -cell
: cell- -cell + ;
: cell- -cell + ;


Line 1,694: Line 1,694:
1- cells over + 2dup mid to midpoint
1- cells over + 2dup mid to midpoint
select midpoint @ ;</syntaxhighlight>
select midpoint @ ;</syntaxhighlight>
<syntaxhighlight lang=forth>create test 4 , 2 , 1 , 3 , 5 ,
<syntaxhighlight lang="forth">create test 4 , 2 , 1 , 3 , 5 ,


test 4 median . \ 2
test 4 median . \ 2
Line 1,702: Line 1,702:
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}


<syntaxhighlight lang=fortran>program Median_Test
<syntaxhighlight lang="fortran">program Median_Test


real :: a(7) = (/ 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 /), &
real :: a(7) = (/ 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 /), &
Line 1,746: Line 1,746:
end program Median_Test</syntaxhighlight>
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> K = N/2
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"> K = N/2
MEDIAN = FINDELEMENT(K + 1,A,N)
MEDIAN = FINDELEMENT(K + 1,A,N)
IF (MOD(N,2).EQ.0) MEDIAN = (FINDELEMENT(K,A,N) + MEDIAN)/2 </syntaxhighlight>
IF (MOD(N,2).EQ.0) MEDIAN = (FINDELEMENT(K,A,N) + MEDIAN)/2 </syntaxhighlight>
Line 1,752: Line 1,752:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Sub quicksort(a() As Double, first As Integer, last As Integer)
Sub quicksort(a() As Double, first As Integer, last As Integer)
Line 1,806: Line 1,806:


=={{header|GAP}}==
=={{header|GAP}}==
<syntaxhighlight lang=gap>Median := function(v)
<syntaxhighlight lang="gap">Median := function(v)
local n, w;
local n, w;
w := SortedList(v);
w := SortedList(v);
Line 1,824: Line 1,824:
===Sort===
===Sort===
Go built-in sort. O(n log n).
Go built-in sort. O(n log n).
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,850: 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().
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
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,883: Line 1,883:
===Quickselect===
===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.
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
<syntaxhighlight lang="go">package main


import (
import (
Line 1,938: Line 1,938:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution (brute force sorting, with arithmetic averaging of dual midpoints (even sizes)):
Solution (brute force sorting, with arithmetic averaging of dual midpoints (even sizes)):
<syntaxhighlight lang=groovy>def median(Iterable col) {
<syntaxhighlight lang="groovy">def median(Iterable col) {
def s = col as SortedSet
def s = col as SortedSet
if (s == null) return null
if (s == null) return null
Line 1,949: Line 1,949:


Test:
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]
<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()
def sz = a.size()


Line 1,984: Line 1,984:


This uses a quick select algorithm and runs in expected O(n) time.
This uses a quick select algorithm and runs in expected O(n) time.
<syntaxhighlight lang=haskell>import Data.List (partition)
<syntaxhighlight lang="haskell">import Data.List (partition)


nth :: Ord t => [t] -> Int -> t
nth :: Ord t => [t] -> Int -> t
Line 2,019: Line 2,019:
Or {{libheader|hstats}}
Or {{libheader|hstats}}


<syntaxhighlight lang=haskell>> Math.Statistics.median [1,9,2,4]
<syntaxhighlight lang="haskell">> Math.Statistics.median [1,9,2,4]
3.0</syntaxhighlight>
3.0</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
If the input has an even number of elements, median is the mean of the middle two values:
If the input has an even number of elements, median is the mean of the middle two values:
<syntaxhighlight lang=HicEst>REAL :: n=10, vec(n)
<syntaxhighlight lang="hicest">REAL :: n=10, vec(n)


vec = RAN(1)
vec = RAN(1)
Line 2,037: Line 2,037:
=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
A quick and dirty solution:
A quick and dirty solution:
<lang>procedure main(args)
<syntaxhighlight lang="text">procedure main(args)
write(median(args))
write(median(args))
end
end
Line 2,057: Line 2,057:
=={{header|J}}==
=={{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:
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'
<syntaxhighlight lang="j"> require 'stats/base'
median 1 9 2 4
median 1 9 2 4
3</syntaxhighlight>
3</syntaxhighlight>
The definition given in the addon script is:
The definition given in the addon script is:
<syntaxhighlight lang=j>midpt=: -:@<:@#
<syntaxhighlight lang="j">midpt=: -:@<:@#
median=: -:@(+/)@((<. , >.)@midpt { /:~)</syntaxhighlight>
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:
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 { /:~
<syntaxhighlight lang="j"> median=: ~.@(<. , >.)@midpt { /:~
median 1 9 2 4
median 1 9 2 4
2 4</syntaxhighlight>
2 4</syntaxhighlight>
Line 2,073: Line 2,073:


Sorting:
Sorting:
<syntaxhighlight lang=java5>// Note: this function modifies the input list
<syntaxhighlight lang="java5">// Note: this function modifies the input list
public static double median(List<Double> list) {
public static double median(List<Double> list) {
Collections.sort(list);
Collections.sort(list);
Line 2,082: Line 2,082:


Using priority queue (which sorts under the hood):
Using priority queue (which sorts under the hood):
<syntaxhighlight lang=java5>public static double median2(List<Double> list) {
<syntaxhighlight lang="java5">public static double median2(List<Double> list) {
PriorityQueue<Double> pq = new PriorityQueue<Double>(list);
PriorityQueue<Double> pq = new PriorityQueue<Double>(list);
int n = list.size();
int n = list.size();
Line 2,097: Line 2,097:
This version operates on objects rather than primitives and uses abstractions to operate on all of the standard numerics.
This version operates on objects rather than primitives and uses abstractions to operate on all of the standard numerics.


<syntaxhighlight lang=java8>
<syntaxhighlight lang="java8">
@FunctionalInterface
@FunctionalInterface
interface MedianFinder<T, R> extends Function<Collection<T>, R> {
interface MedianFinder<T, R> extends Function<Collection<T>, R> {
Line 2,153: Line 2,153:


===ES5===
===ES5===
<syntaxhighlight lang=javascript>function median(ary) {
<syntaxhighlight lang="javascript">function median(ary) {
if (ary.length == 0)
if (ary.length == 0)
return null;
return null;
Line 2,174: Line 2,174:
{{Trans|Haskell}}
{{Trans|Haskell}}


<syntaxhighlight lang=JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 2,228: Line 2,228:


{{Out}}
{{Out}}
<syntaxhighlight lang=JavaScript>[
<syntaxhighlight lang="javascript">[
null,
null,
4,
4,
Line 2,236: Line 2,236:


=={{header|jq}}==
=={{header|jq}}==
<syntaxhighlight lang=jq>def median:
<syntaxhighlight lang="jq">def median:
length as $length
length as $length
| sort as $s
| sort as $s
Line 2,245: Line 2,245:
else $s[$l2]
else $s[$l2]
end
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]
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.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.4
4.25</syntaxhighlight>
4.25</syntaxhighlight>
Line 2,252: Line 2,252:
=={{header|Julia}}==
=={{header|Julia}}==
Julia has a built-in median() function
Julia has a built-in median() function
<syntaxhighlight lang=julia>using Statistics
<syntaxhighlight lang="julia">using Statistics
function median2(n)
function median2(n)
s = sort(n)
s = sort(n)
Line 2,279: Line 2,279:


=={{header|K}}==
=={{header|K}}==
<syntaxhighlight lang=k>
<syntaxhighlight lang="k">
med:{a:x@<x; i:(#a)%2; :[(#a)!2; a@i; {(+/x)%#x} a@i,i-1]}
med:{a:x@<x; i:(#a)%2; :[(#a)!2; a@i; {(+/x)%#x} a@i,i-1]}
v:10*6 _draw 0
v:10*6 _draw 0
Line 2,291: 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:
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>
<syntaxhighlight lang="k">
med:{a:x@<x; i:_(#a)%2
med:{a:x@<x; i:_(#a)%2
$[2!#a; a@i; |a@i,i-1]}
$[2!#a; a@i; |a@i,i-1]}
Line 2,300: Line 2,300:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{works with|Kotlin|1.0+}}
{{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 }
<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>) {
fun main(args: Array<String>) {
Line 2,313: Line 2,313:


Lasso's built in function is "median( value_1, value_2, value_3 )"
Lasso's built in function is "median( value_1, value_2, value_3 )"
<syntaxhighlight lang=Lasso>define median_ext(a::array) => {
<syntaxhighlight lang="lasso">define median_ext(a::array) => {
#a->sort
#a->sort


Line 2,330: Line 2,330:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang=lb>
<syntaxhighlight lang="lb">
dim a( 100), b( 100) ' assumes we will not have vectors of more terms...
dim a( 100), b( 100) ' assumes we will not have vectors of more terms...


Line 2,397: Line 2,397:


=={{header|Lingo}}==
=={{header|Lingo}}==
<syntaxhighlight lang=Lingo>on median (numlist)
<syntaxhighlight lang="lingo">on median (numlist)
-- numlist = numlist.duplicate() -- if input list should not be altered
-- numlist = numlist.duplicate() -- if input list should not be altered
numlist.sort()
numlist.sort()
Line 2,409: Line 2,409:
=={{header|LiveCode}}==
=={{header|LiveCode}}==
LC has median as a built-in function
LC has median as a built-in function
<syntaxhighlight lang=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")
<syntaxhighlight lang="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>
returns 4.4, 4.25</syntaxhighlight>


To make our own, we need own own floor function first
To make our own, we need own own floor function first


<syntaxhighlight lang=LiveCode>function floor n
<syntaxhighlight lang="livecode">function floor n
if n < 0 then
if n < 0 then
return (trunc(n) - 1)
return (trunc(n) - 1)
Line 2,440: Line 2,440:


=={{header|LSL}}==
=={{header|LSL}}==
<syntaxhighlight lang=LSL>integer MAX_ELEMENTS = 10;
<syntaxhighlight lang="lsl">integer MAX_ELEMENTS = 10;
integer MAX_VALUE = 100;
integer MAX_VALUE = 100;
default {
default {
Line 2,478: Line 2,478:


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang=lua>function median (numlist)
<syntaxhighlight lang="lua">function median (numlist)
if type(numlist) ~= 'table' then return numlist end
if type(numlist) ~= 'table' then return numlist end
table.sort(numlist)
table.sort(numlist)
Line 2,491: Line 2,491:
=== Builtin ===
=== Builtin ===
This works for numeric lists or arrays, and is designed for large data sets.
This works for numeric lists or arrays, and is designed for large data sets.
<syntaxhighlight lang=Maple>
<syntaxhighlight lang="maple">
> Statistics:-Median( [ 1, 5, 3, 2, 4 ] );
> Statistics:-Median( [ 1, 5, 3, 2, 4 ] );
3.
3.
Line 2,500: Line 2,500:
=== Using a sort ===
=== 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.
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>
<syntaxhighlight lang="maple">
median1 := proc()
median1 := proc()
local L := sort( [ args ] );
local L := sort( [ args ] );
Line 2,507: Line 2,507:
</syntaxhighlight>
</syntaxhighlight>
For example:
For example:
<syntaxhighlight lang=Maple>
<syntaxhighlight lang="maple">
> median1( 1, 5, 3, 2, 4 ); # 3
> median1( 1, 5, 3, 2, 4 ); # 3
3
3
Line 2,517: Line 2,517:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Built-in function:
Built-in function:
<syntaxhighlight lang=Mathematica>Median[{1, 5, 3, 2, 4}]
<syntaxhighlight lang="mathematica">Median[{1, 5, 3, 2, 4}]
Median[{1, 5, 3, 6, 4, 2}]</syntaxhighlight>
Median[{1, 5, 3, 6, 4, 2}]</syntaxhighlight>
{{out}}
{{out}}
Line 2,523: Line 2,523:
7/2</pre>
7/2</pre>
Custom function:
Custom function:
<syntaxhighlight lang=Mathematica>mymedian[x_List]:=Module[{t=Sort[x],L=Length[x]},
<syntaxhighlight lang="mathematica">mymedian[x_List]:=Module[{t=Sort[x],L=Length[x]},
If[Mod[L,2]==0,
If[Mod[L,2]==0,
(t[[L/2]]+t[[L/2+1]])/2
(t[[L/2]]+t[[L/2+1]])/2
Line 2,531: Line 2,531:
]</syntaxhighlight>
]</syntaxhighlight>
Example of custom function:
Example of custom function:
<syntaxhighlight lang=Mathematica>mymedian[{1, 5, 3, 2, 4}]
<syntaxhighlight lang="mathematica">mymedian[{1, 5, 3, 2, 4}]
mymedian[{1, 5, 3, 6, 4, 2}]</syntaxhighlight>
mymedian[{1, 5, 3, 6, 4, 2}]</syntaxhighlight>
{{out}}
{{out}}
Line 2,539: Line 2,539:
=={{header|MATLAB}}==
=={{header|MATLAB}}==
If the input has an even number of elements, function returns the mean of the middle two values:
If the input has an even number of elements, function returns the mean of the middle two values:
<syntaxhighlight lang=Matlab>function medianValue = findmedian(setOfValues)
<syntaxhighlight lang="matlab">function medianValue = findmedian(setOfValues)
medianValue = median(setOfValues);
medianValue = median(setOfValues);
end</syntaxhighlight>
end</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<syntaxhighlight lang=maxima>/* built-in */
<syntaxhighlight lang="maxima">/* built-in */
median([41, 56, 72, 17, 93, 44, 32]); /* 44 */
median([41, 56, 72, 17, 93, 44, 32]); /* 44 */
median([41, 72, 17, 93, 44, 32]); /* 85/2 */</syntaxhighlight>
median([41, 72, 17, 93, 44, 32]); /* 85/2 */</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<syntaxhighlight lang=MiniScript>list.median = function()
<syntaxhighlight lang="miniscript">list.median = function()
self.sort
self.sort
m = floor(self.len/2)
m = floor(self.len/2)
Line 2,563: Line 2,563:


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<syntaxhighlight lang=MUMPS>MEDIAN(X)
<syntaxhighlight lang="mumps">MEDIAN(X)
;X is assumed to be a list of numbers separated by "^"
;X is assumed to be a list of numbers separated by "^"
;I is a loop index
;I is a loop index
Line 2,589: Line 2,589:
=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang=Nanoquery>import sort
<syntaxhighlight lang="nanoquery">import sort


def median(aray)
def median(aray)
Line 2,604: Line 2,604:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,692: Line 2,692:


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<syntaxhighlight lang=NewLISP>; median.lsp
<syntaxhighlight lang="newlisp">; median.lsp
; oofoe 2012-01-25
; oofoe 2012-01-25


Line 2,726: Line 2,726:
=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang=nim>import algorithm, strutils
<syntaxhighlight lang="nim">import algorithm, strutils
proc median(xs: seq[float]): float =
proc median(xs: seq[float]): float =
Line 2,744: Line 2,744:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Oxford Oberon-2
Oxford Oberon-2
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
MODULE Median;
MODULE Median;
IMPORT Out;
IMPORT Out;
Line 2,836: Line 2,836:


=={{header|Objeck}}==
=={{header|Objeck}}==
<syntaxhighlight lang=objeck>
<syntaxhighlight lang="objeck">
use Structure;
use Structure;


Line 2,871: Line 2,871:


=={{header|OCaml}}==
=={{header|OCaml}}==
<syntaxhighlight lang=ocaml>(* note: this modifies the input array *)
<syntaxhighlight lang="ocaml">(* note: this modifies the input array *)
let median array =
let median array =
let len = Array.length array in
let len = Array.length array in
Line 2,884: Line 2,884:
=={{header|Octave}}==
=={{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.
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)
<syntaxhighlight lang="octave">function y = median2(v)
if (numel(v) < 1)
if (numel(v) < 1)
y = NA;
y = NA;
Line 2,907: Line 2,907:


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx>
<syntaxhighlight lang="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)
call testMedian .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testMedian .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
Line 2,947: Line 2,947:


=={{header|Oz}}==
=={{header|Oz}}==
<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
fun {Median Xs}
fun {Median Xs}
Len = {Length Xs}
Len = {Length Xs}
Line 2,963: Line 2,963:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Sorting solution.
Sorting solution.
<syntaxhighlight lang=parigp>median(v)={
<syntaxhighlight lang="parigp">median(v)={
vecsort(v)[#v\2]
vecsort(v)[#v\2]
};</syntaxhighlight>
};</syntaxhighlight>


Linear-time solution, mostly proof-of-concept but perhaps suitable for large lists.
Linear-time solution, mostly proof-of-concept but perhaps suitable for large lists.
<syntaxhighlight lang=parigp>BFPRT(v,k=#v\2)={
<syntaxhighlight lang="parigp">BFPRT(v,k=#v\2)={
if(#v<15, return(vecsort(v)[k]));
if(#v<15, return(vecsort(v)[k]));
my(u=List(),pivot,left=List(),right=List());
my(u=List(),pivot,left=List(),right=List());
Line 2,992: Line 2,992:
=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Free_Pascal}}
{{works with|Free_Pascal}}
<syntaxhighlight lang=pascal>Program AveragesMedian(output);
<syntaxhighlight lang="pascal">Program AveragesMedian(output);


type
type
Line 3,059: Line 3,059:
=={{header|Perl}}==
=={{header|Perl}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang=perl>sub median {
<syntaxhighlight lang="perl">sub median {
my @a = sort {$a <=> $b} @_;
my @a = sort {$a <=> $b} @_;
return ($a[$#a/2] + $a[@a/2]) / 2;
return ($a[$#a/2] + $a[@a/2]) / 2;
Line 3,066: Line 3,066:
=={{header|Phix}}==
=={{header|Phix}}==
The obvious simple way:
The obvious simple way:
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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: Line 3,083:
It is also possible to use the [[Quickselect_algorithm#Phix|quick_select]] routine for a small (20%) performance improvement,
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.
which as suggested below may with luck be magnified by retaining any partially sorted results.
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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: Line 3,100:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt


def median /# l -- n #/
def median /# l -- n #/
Line 3,117: Line 3,117:
=={{header|PHP}}==
=={{header|PHP}}==
This solution uses the sorting method of finding the median.
This solution uses the sorting method of finding the median.
<syntaxhighlight lang=php>
<syntaxhighlight lang="php">
function median($arr)
function median($arr)
{
{
Line 3,138: Line 3,138:


=={{header|Picat}}==
=={{header|Picat}}==
<syntaxhighlight lang=Picat>go =>
<syntaxhighlight lang="picat">go =>
Lists = [
Lists = [
[1.121,10.3223,3.41,12.1,0.01],
[1.121,10.3223,3.41,12.1,0.01],
Line 3,177: Line 3,177:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp>(de median (Lst)
<syntaxhighlight lang="picolisp">(de median (Lst)
(let N (length Lst)
(let N (length Lst)
(if (bit? 1 N)
(if (bit? 1 N)
Line 3,196: Line 3,196:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=pli>call sort(A);
<syntaxhighlight lang="pli">call sort(A);
n = dimension(A,1);
n = dimension(A,1);
if iand(n,1) = 1 then /* an odd number of elements */
if iand(n,1) = 1 then /* an odd number of elements */
Line 3,208: Line 3,208:
All statistical properties could easily be added to the output object.
All statistical properties could easily be added to the output object.


<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
function Measure-Data
function Measure-Data
{
{
Line 3,279: Line 3,279:
}
}
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
$statistics = Measure-Data 4, 5, 6, 7, 7, 7, 8, 1, 1, 1, 2, 3
$statistics = Measure-Data 4, 5, 6, 7, 7, 7, 8, 1, 1, 1, 2, 3
$statistics
$statistics
Line 3,296: Line 3,296:
</pre>
</pre>
Median only:
Median only:
<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
$statistics.Median
$statistics.Median
</syntaxhighlight>
</syntaxhighlight>
Line 3,305: Line 3,305:


=={{header|Processing}}==
=={{header|Processing}}==
<syntaxhighlight lang=Processing>void setup() {
<syntaxhighlight lang="processing">void setup() {
float[] numbers = {3.1, 4.1, 5.9, 2.6, 5.3, 5.8};
float[] numbers = {3.1, 4.1, 5.9, 2.6, 5.3, 5.8};
println(median(numbers));
println(median(numbers));
Line 3,322: Line 3,322:


=={{header|Prolog}}==
=={{header|Prolog}}==
<syntaxhighlight lang=Prolog>median(L, Z) :-
<syntaxhighlight lang="prolog">median(L, Z) :-
length(L, Length),
length(L, Length),
I is Length div 2,
I is Length div 2,
Line 3,334: Line 3,334:
=={{header|Pure}}==
=={{header|Pure}}==
Inspired by the Haskell version.
Inspired by the Haskell version.
<syntaxhighlight lang=Pure>median x = (/(2-rem)) $ foldl1 (+) $ take (2-rem) $ drop (mid-(1-rem)) $ sort (<=) x
<syntaxhighlight lang="pure">median x = (/(2-rem)) $ foldl1 (+) $ take (2-rem) $ drop (mid-(1-rem)) $ sort (<=) x
when len = # x;
when len = # x;
mid = len div 2;
mid = len div 2;
Line 3,346: Line 3,346:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic>Procedure.d median(Array values.d(1), length.i)
<syntaxhighlight lang="purebasic">Procedure.d median(Array values.d(1), length.i)
If length = 0 : ProcedureReturn 0.0 : EndIf
If length = 0 : ProcedureReturn 0.0 : EndIf
SortArray(values(), #PB_Sort_Ascending)
SortArray(values(), #PB_Sort_Ascending)
Line 3,383: Line 3,383:


=={{header|Python}}==
=={{header|Python}}==
<syntaxhighlight lang=python>def median(aray):
<syntaxhighlight lang="python">def median(aray):
srtd = sorted(aray)
srtd = sorted(aray)
alen = len(srtd)
alen = len(srtd)
Line 3,397: Line 3,397:
{{trans|Octave}}
{{trans|Octave}}


<syntaxhighlight lang=rsplus>omedian <- function(v) {
<syntaxhighlight lang="rsplus">omedian <- function(v) {
if ( length(v) < 1 )
if ( length(v) < 1 )
NA
NA
Line 3,419: Line 3,419:


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang=Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define (median numbers)
(define (median numbers)
(define sorted (list->vector (sort (vector->list numbers) <)))
(define sorted (list->vector (sort (vector->list numbers) <)))
Line 3,438: Line 3,438:


{{works with|Rakudo|2016.08}}
{{works with|Rakudo|2016.08}}
<syntaxhighlight lang=perl6>sub median {
<syntaxhighlight lang="raku" line>sub median {
my @a = sort @_;
my @a = sort @_;
return (@a[(*-1) div 2] + @a[* div 2]) / 2;
return (@a[(*-1) div 2] + @a[* div 2]) / 2;
Line 3,450: Line 3,450:
<br>
<br>
In a slightly more compact way:
In a slightly more compact way:
<syntaxhighlight lang=perl6>sub median { @_.sort[(*-1)/2, */2].sum / 2 }</syntaxhighlight>
<syntaxhighlight lang="raku" line>sub median { @_.sort[(*-1)/2, */2].sum / 2 }</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<syntaxhighlight lang=rebol>
<syntaxhighlight lang="rebol">
median: func [
median: func [
"Returns the midpoint value in a series of numbers; half the values are above, half are below."
"Returns the midpoint value in a series of numbers; half the values are above, half are below."
Line 3,472: Line 3,472:


=={{header|ReScript}}==
=={{header|ReScript}}==
<syntaxhighlight lang=ReScript>let median = (arr) =>
<syntaxhighlight lang="rescript">let median = (arr) =>
{
{
let float_compare = (a, b) => {
let float_compare = (a, b) => {
Line 3,505: Line 3,505:


=={{header|REXX}}==
=={{header|REXX}}==
<syntaxhighlight lang=rexx>/*REXX program finds the median of a vector (and displays the vector and median).*/
<syntaxhighlight lang="rexx">/*REXX program finds the median of a vector (and displays the vector and median).*/
/* ══════════vector════════════ ══show vector═══ ════════show result═══════════ */
/* ══════════vector════════════ ══show vector═══ ════════show result═══════════ */
v= 1 9 2 4 ; say "vector" v; say 'median──────►' median(v); say
v= 1 9 2 4 ; say "vector" v; say 'median──────►' median(v); say
Line 3,545: Line 3,545:


=={{header|Ring}}==
=={{header|Ring}}==
<syntaxhighlight lang=ring>
<syntaxhighlight lang="ring">
aList = [5,4,2,3]
aList = [5,4,2,3]
see "medium : " + median(aList) + nl
see "medium : " + median(aList) + nl
Line 3,558: Line 3,558:


=={{header|Ruby}}==
=={{header|Ruby}}==
<syntaxhighlight lang=ruby>def median(ary)
<syntaxhighlight lang="ruby">def median(ary)
return nil if ary.empty?
return nil if ary.empty?
mid, rem = ary.length.divmod(2)
mid, rem = ary.length.divmod(2)
Line 3,574: Line 3,574:


Alternately:
Alternately:
<syntaxhighlight lang=ruby>def median(aray)
<syntaxhighlight lang="ruby">def median(aray)
srtd = aray.sort
srtd = aray.sort
alen = srtd.length
alen = srtd.length
Line 3,581: Line 3,581:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<syntaxhighlight lang=Runbasic>sqliteconnect #mem, ":memory:"
<syntaxhighlight lang="runbasic">sqliteconnect #mem, ":memory:"
mem$ = "CREATE TABLE med (x float)"
mem$ = "CREATE TABLE med (x float)"
#mem execute(mem$)
#mem execute(mem$)
Line 3,622: Line 3,622:
Sorting, then obtaining the median element:
Sorting, then obtaining the median element:


<syntaxhighlight lang=rust>fn median(mut xs: Vec<f64>) -> f64 {
<syntaxhighlight lang="rust">fn median(mut xs: Vec<f64>) -> f64 {
// sort in ascending order, panic on f64::NaN
// sort in ascending order, panic on f64::NaN
xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );
xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );
Line 3,644: Line 3,644:
{{works with|Scala|2.8}} (See the Scala discussion on [[Mean]] for more information.)
{{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]) = {
<syntaxhighlight lang="scala">def median[T](s: Seq[T])(implicit n: Fractional[T]) = {
import n._
import n._
val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2)
val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2)
Line 3,657: Line 3,657:
{{trans|Python}}
{{trans|Python}}
Using Rosetta Code's [[Bubble_Sort#Scheme|bubble-sort function]]
Using Rosetta Code's [[Bubble_Sort#Scheme|bubble-sort function]]
<syntaxhighlight lang=Scheme>(define (median l)
<syntaxhighlight lang="scheme">(define (median l)
(* (+ (list-ref (bubble-sort l >) (round (/ (- (length l) 1) 2)))
(* (+ (list-ref (bubble-sort l >) (round (/ (- (length l) 1) 2)))
(list-ref (bubble-sort l >) (round (/ (length l) 2)))) 0.5))</syntaxhighlight>
(list-ref (bubble-sort l >) (round (/ (length l) 2)))) 0.5))</syntaxhighlight>


Using [http://srfi.schemers.org/srfi-95/srfi-95.html SRFI-95]:
Using [http://srfi.schemers.org/srfi-95/srfi-95.html SRFI-95]:
<syntaxhighlight lang=Scheme>(define (median l)
<syntaxhighlight lang="scheme">(define (median l)
(* (+ (list-ref (sort l less?) (round (/ (- (length l) 1) 2)))
(* (+ (list-ref (sort l less?) (round (/ (- (length l) 1) 2)))
(list-ref (sort l less?) (round (/ (length l) 2)))) 0.5))</syntaxhighlight>
(list-ref (sort l less?) (round (/ (length l) 2)))) 0.5))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";
Line 3,698: Line 3,698:
=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
SenseTalk has a built-in median function. This example also shows the implementation of a customMedian function that returns the same results.
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]
<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]
put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]


Line 3,714: Line 3,714:
end customMedian</syntaxhighlight>
end customMedian</syntaxhighlight>
Output:
Output:
<syntaxhighlight lang=sensetalk>4.4
<syntaxhighlight lang="sensetalk">4.4
5
5
4.4
4.4
Line 3,720: Line 3,720:


=={{header|Sidef}}==
=={{header|Sidef}}==
<syntaxhighlight lang=ruby>func median(arry) {
<syntaxhighlight lang="ruby">func median(arry) {
var srtd = arry.sort;
var srtd = arry.sort;
var alen = srtd.length;
var alen = srtd.length;
Line 3,727: Line 3,727:


=={{header|Slate}}==
=={{header|Slate}}==
<syntaxhighlight lang=slate>s@(Sequence traits) median
<syntaxhighlight lang="slate">s@(Sequence traits) median
[
[
s isEmpty
s isEmpty
Line 3,739: Line 3,739:
].</syntaxhighlight>
].</syntaxhighlight>


<syntaxhighlight lang=slate>inform: { 4.1 . 5.6 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } median.
<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>
inform: { 4.1 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } median.</syntaxhighlight>


Line 3,745: Line 3,745:
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}


<syntaxhighlight lang=smalltalk>OrderedCollection extend [
<syntaxhighlight lang="smalltalk">OrderedCollection extend [
median [
median [
self size = 0
self size = 0
Line 3,759: Line 3,759:
].</syntaxhighlight>
].</syntaxhighlight>


<syntaxhighlight lang=smalltalk>{ 4.1 . 5.6 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } asOrderedCollection
<syntaxhighlight lang="smalltalk">{ 4.1 . 5.6 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } asOrderedCollection
median displayNl.
median displayNl.
{ 4.1 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } asOrderedCollection
{ 4.1 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } asOrderedCollection
Line 3,767: 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).
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
<syntaxhighlight lang="stata">set obs 100000
gen x=rbeta(0.2,1.3)
gen x=rbeta(0.2,1.3)
quietly summarize x, detail
quietly summarize x, detail
Line 3,774: Line 3,774:
Here is a straightforward implementation using '''[https://www.stata.com/help.cgi? sort]'''.
Here is a straightforward implementation using '''[https://www.stata.com/help.cgi? sort]'''.


<syntaxhighlight lang=stata>program calcmedian, rclass sortpreserve
<syntaxhighlight lang="stata">program calcmedian, rclass sortpreserve
sort `1'
sort `1'
if mod(_N,2)==0 {
if mod(_N,2)==0 {
Line 3,788: Line 3,788:


=={{header|Tcl}}==
=={{header|Tcl}}==
<syntaxhighlight lang=tcl>proc median args {
<syntaxhighlight lang="tcl">proc median args {
set list [lsort -real $args]
set list [lsort -real $args]
set len [llength $list]
set len [llength $list]
Line 3,808: Line 3,808:


Using the built-in function:
Using the built-in function:
<syntaxhighlight lang=ti83b>median({1.1, 2.5, 0.3241})</syntaxhighlight>
<syntaxhighlight lang="ti83b">median({1.1, 2.5, 0.3241})</syntaxhighlight>


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==


<syntaxhighlight lang=ti89b>median({3, 4, 1, -8.4, 7.2, 4, 1, 1})</syntaxhighlight>
<syntaxhighlight lang="ti89b">median({3, 4, 1, -8.4, 7.2, 4, 1, 1})</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
the simple way (sort first and then look in the middle)
the simple way (sort first and then look in the middle)
<syntaxhighlight lang=Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import flo
#import flo


median = fleq-<; @K30K31X eql?\~&rh div\2.+ plus@lzPrhPX</syntaxhighlight>
median = fleq-<; @K30K31X eql?\~&rh div\2.+ plus@lzPrhPX</syntaxhighlight>
test program, once with an odd length and once with an even length vector
test program, once with an odd length and once with an even length vector
<syntaxhighlight lang=Ursala>#cast %eW
<syntaxhighlight lang="ursala">#cast %eW


examples =
examples =
Line 3,835: 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.
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) {
<syntaxhighlight lang="vala">int compare_numbers(void* a_ref, void* b_ref) {
double a = *(double*) a_ref;
double a = *(double*) a_ref;
double b = *(double*) b_ref;
double b = *(double*) b_ref;
Line 3,858: Line 3,858:
{{trans|Phix}}
{{trans|Phix}}
Uses [[Quickselect_algorithm#VBA|quick select]].
Uses [[Quickselect_algorithm#VBA|quick select]].
<syntaxhighlight lang=vb>Private Function medianq(s As Variant) As Double
<syntaxhighlight lang="vb">Private Function medianq(s As Variant) As Double
Dim res As Double, tmp As Integer
Dim res As Double, tmp As Integer
Dim l As Integer, k As Integer
Dim l As Integer, k As Integer
Line 3,884: Line 3,884:
The result is returned in text register @10. In case of even number of items, the lower middle value is returned.
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)
<syntaxhighlight lang="vedit">Sort(0, File_Size, NOCOLLATE+NORESTORE)
EOF Goto_Line(Cur_Line/2)
EOF Goto_Line(Cur_Line/2)
Reg_Copy(10, 1)</syntaxhighlight>
Reg_Copy(10, 1)</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
<syntaxhighlight lang=vlang>fn main() {
<syntaxhighlight lang="vlang">fn main() {
println(median([3, 1, 4, 1])) // prints 2
println(median([3, 1, 4, 1])) // prints 2
println(median([3, 1, 4, 1, 5])) // prints 3
println(median([3, 1, 4, 1, 5])) // prints 3
Line 3,911: Line 3,911:
</pre>
</pre>
If you use math.stats module the list parameter must be sorted
If you use math.stats module the list parameter must be sorted
<lang>import math.stats
<syntaxhighlight lang="text">import math.stats
fn main() {
fn main() {
println(stats.median<int>([1, 1, 3, 4])) // prints 2
println(stats.median<int>([1, 1, 3, 4])) // prints 2
Line 3,918: Line 3,918:


=={{header|Wortel}}==
=={{header|Wortel}}==
<syntaxhighlight lang=wortel>@let {
<syntaxhighlight lang="wortel">@let {
; iterative
; iterative
med1 &l @let {a @sort l s #a i @/s 2 ?{%%s 2 ~/ 2 +`-i 1 a `i a `i a}}
med1 &l @let {a @sort l s #a i @/s 2 ?{%%s 2 ~/ 2 +`-i 1 a `i a `i a}}
Line 3,938: Line 3,938:
{{libheader|Wren-math}}
{{libheader|Wren-math}}
{{libheader|Wren-queue}}
{{libheader|Wren-queue}}
<syntaxhighlight lang=ecmascript>import "/sort" for Sort, Find
<syntaxhighlight lang="ecmascript">import "/sort" for Sort, Find
import "/math" for Nums
import "/math" for Nums
import "/queue" for PriorityQueue
import "/queue" for PriorityQueue
Line 3,984: Line 3,984:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{trans|Lua}}
{{trans|Lua}}
<syntaxhighlight lang=Yabasic>sub floor(x)
<syntaxhighlight lang="yabasic">sub floor(x)
return int(x + .05)
return int(x + .05)
end sub
end sub
Line 4,044: Line 4,044:
=={{header|zkl}}==
=={{header|zkl}}==
Using the [[Quickselect algorithm#zkl]] for O(n) time:
Using the [[Quickselect algorithm#zkl]] for O(n) time:
<syntaxhighlight lang=zkl>var quickSelect=Import("quickSelect").qselect;
<syntaxhighlight lang="zkl">var quickSelect=Import("quickSelect").qselect;


fcn median(xs){
fcn median(xs){
Line 4,051: Line 4,051:
( quickSelect(xs,n/2-1) + quickSelect(xs,n/2) )/2;
( quickSelect(xs,n/2-1) + quickSelect(xs,n/2) )/2;
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=zkl>median(T( 5.1, 2.6, 6.2, 8.8, 4.6, 4.1 )); //-->4.85
<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>
median(T( 5.1, 2.6, 8.8, 4.6, 4.1 )); //-->4.6</syntaxhighlight>


=={{header|Zoea}}==
=={{header|Zoea}}==
<syntaxhighlight lang=Zoea>
<syntaxhighlight lang="zoea">
program: median
program: median
case: 1
case: 1
Line 4,072: Line 4,072:


=={{header|zonnon}}==
=={{header|zonnon}}==
<syntaxhighlight lang=zonnon>
<syntaxhighlight lang="zonnon">
module Averages;
module Averages;