Averages/Median: Difference between revisions
m
syntax highlighting fixup automation
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 20:
=={{header|11l}}==
{{trans|Python}}
<
V srtd = sorted(aray)
V alen = srtd.len
Line 26:
print(median([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]))
print(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]))</
{{out}}
<pre>
Line 36:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<
DEFINE PTR="CARD"
Line 103:
Test(a,i)
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Averages_Median.png Screenshot from Atari 8-bit computer]
Line 118:
=={{header|Ada}}==
<
procedure FindMedian is
Line 148:
Ada.Float_Text_IO.Put( median_val );
Ada.Text_IO.New_line;
end FindMedian;</
=={{header|ALGOL 68}}==
{{trans|C}}<
# Return the k-th smallest item in array x of length len #
Line 215:
"<: ", whole (less,0), new line,
">: ", whole (more, 0), new line,
"=: ", whole (eq, 0), new line))</
Sample output:
<pre>length: 97738
Line 226:
=={{header|AntLang}}==
AntLang has a built-in median function.
<syntaxhighlight lang
=={{header|APL}}==
<
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
If you prefer an index origin of 1, use this code instead:
<
⎕IO←1
median←{v←⍵[⍋⍵] ⋄ 0.5×v[⌈0.5×⍴v]+v[⌊1+0.5×⍴v]}
</syntaxhighlight>
This code was tested with ngn/apl and Dyalog 12.1. You can try this function online with [http://ngn.github.io/apl/web/index.html#code=median%u2190%7Bv%u2190%u2375%5B%u234B%u2375%5D%u22C4.5%D7v%5B%u2308%AF1+.5%D7%u2374v%5D+v%5B%u230A.5%D7%u2374v%5D%7D ngn/apl]. Note that ngn/apl currently only supports index origin 0. Examples:
Line 276:
=={{header|AppleScript}}==
===By iteration===
<
set med to medi(alist)
Line 319:
return max
end findmax</
{{output}}
<syntaxhighlight lang
===Composing functionally===
Line 328:
{{Trans|JavaScript}}
{{Trans|Haskell}}
<
-- median :: [Num] -> Num
Line 433:
missing value
end if
end uncons</
{{Out}}
<
----
===Quickselect===
<
on getMedian(theList, l, r)
if (theList is {}) then return theList
Line 512:
set end of testList to (random number 500) / 5
end repeat
return {|numbers|:testList, median:getMedian(testList, 1, (count testList))}</
{{output}}
<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===
<
on getMedian(theList, l, r)
script o
Line 579:
end repeat
return {|numbers|:testList, median:getMedian(testList, 1, (count testList))}
</syntaxhighlight>
{{output}}
<
=={{header|Applesoft BASIC}}==
<
110 K = INT(L/2) : GOSUB 150
120 R = X(K)
Line 609:
300 REMSWAP
310 H = X(P1):X(P1) = X(P2)
320 X(P2) = H: RETURN</
L = 11 : GOSUB 100MEDIAN
? R</
=={{header|Arturo}}==
<
arr2: [1 2 3 4 5 6]
print median arr
print median arr2</
{{out}}
Line 628:
=={{header|AutoHotkey}}==
Takes the lower of the middle two if length is even
<
MsgBox % median(seq, "`,") ; 4.1
Line 637:
median := Floor(seq0 / 2)
Return seq%median%
}</
=={{header|AWK}}==
Line 643:
AWK arrays can be passed as parameters, but not returned, so they are usually global.
<
BEGIN {
Line 689:
print ""
}
</syntaxhighlight>
Example output:
Line 697:
=={{header|BaCon}}==
<
DECLARE b[] = { 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING
Line 708:
SORT b
PRINT "Median of b: ", Median(b)</
{{out}}
<pre>
Line 726:
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>.
<
DIM vec1(10) AS SINGLE, vec2(11) AS SINGLE, n AS INTEGER
Line 755:
median = (v(INT((ub + lb) / 2)) + v(INT((ub + lb) / 2) + 1)) / 2
END IF
END FUNCTION</
See also: [[#BBC BASIC|BBC BASIC]], [[#Liberty BASIC|Liberty BASIC]], [[#PureBasic|PureBasic]], [[#TI-83 BASIC|TI-83 BASIC]], [[#TI-89 BASIC|TI-89 BASIC]].
Line 761:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
Sort% = FN_sortinit(0,0)
Line 777:
CALL Sort%, a(0)
= (a(C% DIV 2) + a((C%-1) DIV 2)) / 2
</syntaxhighlight>
Output:
<pre>Median of a() is 4.4
Line 794:
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.
<
begin decimals end int list med med1 med2 num number
. 0:?list
Line 818:
)
& !med
);</
Line 834:
=={{header|C}}==
<
#include <stdlib.h>
Line 864:
printf("flist2 median is %7.2f\n", median(&flist2)); /* 4.60 */
return 0;
}</
===Quickselect algorithm===
Average O(n) time:
<
#include <stdlib.h>
#include <time.h>
Line 946:
return 0;
}
</syntaxhighlight>
Output:
<
median: 0.000473
<: 496010
>: 496010
=: 1</
=={{header|C sharp|C#}}==
<
using System.Linq;
Line 989:
}
}
</syntaxhighlight>
=={{header|C++}}==
This function runs in linear time on average.
<
// inputs must be random-access iterators of doubles
Line 1,024:
return 0;
}</
===Order Statistic Tree===
Uses a GNU C++ policy-based data structure to compute median in O(log n) time.
{{libheader|gnu_pbds}}
<
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
Line 1,068:
return 0;
}
</syntaxhighlight>
=={{header|Clojure}}==
Simple:
<
(let [ns (sort ns)
cnt (count ns)
Line 1,078:
(if (odd? cnt)
(nth ns mid)
(/ (+ (nth ns mid) (nth ns (dec mid))) 2))))</
=={{header|COBOL}}==
Intrinsic function:
<
=={{header|Common Lisp}}==
Line 1,088:
The recursive partitioning solution, without the median of medians optimization.
<
"Select nth element in list, ordered by predicate, modifying list."
(do ((pivot (pop list))
Line 1,110:
(defun median (list predicate)
(select-nth (floor (length list) 2) list predicate))</
=={{header|Crystal}}==
<
srtd = ary.sort
alen = srtd.size
Line 1,127:
a = [5.0]
puts median a
</syntaxhighlight>
{{out}}
Line 1,137:
=={{header|D}}==
<
T median(T)(T[] nums) pure nothrow {
Line 1,153:
auto a2 = [5.1, 2.6, 8.8, 4.6, 4.1];
writeln("Odd median: ", a2.median);
}</
{{out}}
<pre>Even median: 4.85
Line 1,159:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 1,181:
Writeln(Median(TDoubleDynArray.Create(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)));
Writeln(Median(TDoubleDynArray.Create(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)));
end.</
=={{header|E}}==
Line 1,187:
TODO: Use the selection algorithm, whatever that is [[Category:E examples needing attention]]
<
def sorted := list.sort()
def count := sorted.size()
Line 1,197:
return (sorted[mid1] + sorted[mid2]) / 2
}
}</
<
# value: 2
? median([1,9,2,4])
# value: 3.0</
=={{header|EasyLang}}==
Line 1,247:
test[] = [ 4.1 7.2 1.7 9.3 4.4 3.2 ]
call median test[] med
print med</
<pre>
Line 1,255:
=={{header|EchoLisp}}==
<
(define (median L) ;; O(n log(n))
(set! L (vector-sort! < (list->vector L)))
Line 1,271:
(median (iota 10001))
→ 5000
</syntaxhighlight>
=={{header|Elena}}==
ELENA 5.0 :
<
import system'math;
import extensions;
Line 1,314:
console.readChar()
}</
{{out}}
<pre>
Line 1,323:
=={{header|Elixir}}==
{{trans|Erlang}}
<
def median([]), do: nil
def median(list) do
Line 1,338:
Enum.each(1..6, fn i ->
(for _ <- 1..i, do: :rand.uniform(6)) |> median.()
end)</
{{out}}
Line 1,352:
=={{header|Erlang}}==
<
-import(lists, [nth/2, sort/1]).
-compile(export_all).
Line 1,415:
end.
</syntaxhighlight>
=={{header|ERRE}}==
Line 1,455:
PRINT(R)
END PROGRAM
</syntaxhighlight>
Ouput is 5.95
Line 1,464:
v. Moreover it can search for the p median, not only the p=0.5 median.
<
>type median
function median (x, v: none, p)
Line 1,515:
>0.2*10+0.8*1
2.8
</syntaxhighlight>
=={{header|Euphoria}}==
<
atom min,k
-- Selection sort of half+1
Line 1,542:
end function
? median({ 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5 })</
Output:
Line 1,551:
Assuming the values are entered in the A column, type into any cell which will not be part of the list :
<
=MEDIAN(A1:A10)
</syntaxhighlight>
Assuming 10 values will be entered, alternatively, you can just type
<
=MEDIAN(
</syntaxhighlight>
and then select the start and end cells, not necessarily in the same row or column.
Line 1,575:
9
0
</syntaxhighlight>
=={{header|F Sharp|F#}}==
Median of Medians algorithm implementation
<
let rec splitToFives list =
match list with
Line 1,624:
let z' = [1.;5.;2.;8.;7.]
start z'
</syntaxhighlight>
=={{header|Factor}}==
The quicksort-style solution, with random pivoting. Takes the lesser of the two medians for even sequences.
<
IN: median
Line 1,654:
: median ( seq -- median )
dup length 1 - 2 / floor nth-in-order ;</
Usage:
<
5
( scratchpad ) 10 iota median .
4</
=={{header|Forth}}==
This uses the O(n) algorithm derived from [[quicksort]].
<
: cell- -cell + ;
Line 1,693:
: median ( array len -- m )
1- cells over + 2dup mid to midpoint
select midpoint @ ;</
<
test 4 median . \ 2
test 5 median . \ 3</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
real :: a(7) = (/ 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 /), &
Line 1,744:
end function median
end program Median_Test</
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, <
MEDIAN = FINDELEMENT(K + 1,A,N)
IF (MOD(N,2).EQ.0) MEDIAN = (FINDELEMENT(K,A,N) + MEDIAN)/2 </
As well as returning a result, the function possibly re-arranges the elements of the array, which is not "pure" behaviour. Not to the degree of fully sorting them, merely that all elements before K are not larger than A(K) as it now is, and all elements after K are not smaller than A(K).
=={{header|FreeBASIC}}==
<
Sub quicksort(a() As Double, first As Integer, last As Integer)
Line 1,797:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,806:
=={{header|GAP}}==
<
local n, w;
w := SortedList(v);
Line 1,819:
# 44
Median(b);
# 85/2</
=={{header|Go}}==
===Sort===
Go built-in sort. O(n log n).
<
import (
Line 1,844:
}
return m
}</
===Partial selection sort===
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().
<
import "fmt"
Line 1,880:
}
return list[k]
}</
===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.
<
import (
Line 1,934:
}
return a[0]
}</
=={{header|Groovy}}==
Solution (brute force sorting, with arithmetic averaging of dual midpoints (even sizes)):
<
def s = col as SortedSet
if (s == null) return null
Line 1,946:
def l = s.collect { it }
n%2 == 1 ? l[m] : (l[m] + l[m-1])/2
}</
Test:
<
def sz = a.size()
Line 1,955:
println """${median(a[0..<(sz-it)])} == median(${a[0..<(sz-it)]})
${median(a[it..<sz])} == median(${a[it..<sz]})"""
}</
Output:
Line 1,984:
This uses a quick select algorithm and runs in expected O(n) time.
<
nth :: Ord t => [t] -> Int -> t
Line 2,009:
[[], [7], [5, 3, 4], [5, 4, 2, 3], [3, 4, 1, -8.4, 7.2, 4, 1, 1.2]]
where
printMay = maybe (putStrLn "(not defined)") print</
{{Out}}
<pre>(not defined)
Line 2,019:
Or {{libheader|hstats}}
<
3.0</
=={{header|HicEst}}==
If the input has an even number of elements, median is the mean of the middle two values:
<
vec = RAN(1)
Line 2,033:
ELSE
median = ( vec(n/2) + vec(n/2 + 1) ) / 2
ENDIF</
=={{header|Icon}} and {{header|Unicon}}==
Line 2,046:
return if n % 2 = 1 then A[n/2+1]
else (A[n/2]+A[n/2+1])/2.0 | 0 # 0 if empty list
end</
Sample outputs:
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:
<
median 1 9 2 4
3</
The definition given in the addon script is:
<
median=: -:@(+/)@((<. , >.)@midpt { /:~)</
If, for an even number of elements, both values were desired when those two values are distinct, then the following implementation would suffice:
<
median 1 9 2 4
2 4</
=={{header|Java}}==
Line 2,073:
Sorting:
<
public static double median(List<Double> list) {
Collections.sort(list);
return (list.get(list.size() / 2) + list.get((list.size() - 1) / 2)) / 2;
}</
{{works with|Java|1.5+}}
Using priority queue (which sorts under the hood):
<
PriorityQueue<Double> pq = new PriorityQueue<Double>(list);
int n = list.size();
Line 2,091:
else
return (pq.poll() + pq.poll()) / 2.0;
}</
{{works with|Java|1.8+}}
Line 2,097:
This version operates on objects rather than primitives and uses abstractions to operate on all of the standard numerics.
<
@FunctionalInterface
interface MedianFinder<T, R> extends Function<Collection<T>, R> {
Line 2,148:
public static BigDecimal bigDecimals(Collection<BigDecimal> bigDecimalCollection) { return BIG_DECIMALS.apply(bigDecimalCollection); }
}
</syntaxhighlight>
=={{header|JavaScript}}==
===ES5===
<
if (ary.length == 0)
return null;
Line 2,167:
median([5,3,4]); // 4
median([5,4,2,3]); // 3.5
median([3,4,1,-8.4,7.2,4,1,1.2]); // 2.1</
===ES6===
Line 2,174:
{{Trans|Haskell}}
<
'use strict';
Line 2,225:
[3, 4, 1, -8.4, 7.2, 4, 1, 1.2]
].map(median);
})();</
{{Out}}
<
null,
4,
3.5,
2.1
]</
=={{header|jq}}==
<
length as $length
| sort as $s
Line 2,245:
else $s[$l2]
end
end ;</
[4.1, 7.2, 1.7, 9.3, 4.4, 3.2]</
4.4
4.25</
=={{header|Julia}}==
Julia has a built-in median() function
<
function median2(n)
s = sort(n)
Line 2,266:
b = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2]
@show a b median2(a) median(a) median2(b) median(b) </
{{out}}
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,288:
med[1_ v]
2.281911
</syntaxhighlight>
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]}
med[v]
2.2819 4.8547
</syntaxhighlight>
=={{header|Kotlin}}==
{{works with|Kotlin|1.0+}}
<
fun main(args: Array<String>) {
Line 2,306:
median(listOf(5.0, 4.0, 2.0, 3.0)).let { println(it) } // 3.5
median(listOf(3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2)).let { println(it) } // 2.1
}</
=={{header|Lasso}}==
Line 2,313:
Lasso's built in function is "median( value_1, value_2, value_3 )"
<
#a->sort
Line 2,327:
median_ext(array(3,2,7,6)) // 4.5
median_ext(array(3,2,9,7,6)) // 6</
=={{header|Liberty BASIC}}==
<syntaxhighlight lang=lb>
dim a( 100), b( 100) ' assumes we will not have vectors of more terms...
Line 2,375:
if middle <>intmiddle then median= a( 1 +intmiddle) else median =( a( intmiddle) +a( intmiddle +1)) /2
end function
</syntaxhighlight>
<pre>
4.1 5.6 7.2 1.7 9.3 4.4 3.2
Line 2,397:
=={{header|Lingo}}==
<
-- numlist = numlist.duplicate() -- if input list should not be altered
numlist.sort()
Line 2,405:
return (numlist[numlist.count/2]+numlist[numlist.count/2+1])/2.0
end if
end</
=={{header|LiveCode}}==
LC has median as a built-in function
<
returns 4.4, 4.25</
To make our own, we need own own floor function first
<
if n < 0 then
return (trunc(n) - 1)
Line 2,437:
returns the same as the built-in median, viz.
put median2("4.1,5.6,7.2,1.7,9.3,4.4,3.2") & "," & median2("4.1,7.2,1.7,9.3,4.4,3.2")
4.4,4.25</
=={{header|LSL}}==
<
integer MAX_VALUE = 100;
default {
Line 2,461:
llOwnerSay(" Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst));
}
}</
Output:
<pre>
Line 2,478:
=={{header|Lua}}==
<
if type(numlist) ~= 'table' then return numlist end
table.sort(numlist)
Line 2,486:
print(median({4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}))
print(median({4.1, 7.2, 1.7, 9.3, 4.4, 3.2}))</
=={{header|Maple}}==
=== Builtin ===
This works for numeric lists or arrays, and is designed for large data sets.
<
> Statistics:-Median( [ 1, 5, 3, 2, 4 ] );
3.
Line 2,497:
> Statistics:-Median( [ 1, 5, 3, 6, 2, 4 ] );
3.50000000000000
</syntaxhighlight>
=== 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.
<
median1 := proc()
local L := sort( [ args ] );
( L[ iquo( 1 + nargs, 2 ) ] + L[ 1 + iquo( nargs, 2 ) ] ) / 2
end proc:
</syntaxhighlight>
For example:
<
> median1( 1, 5, 3, 2, 4 ); # 3
3
Line 2,513:
> median1( 1, 5, 3, 6, 4, 2 ); # 7/2
7/2
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Built-in function:
<
Median[{1, 5, 3, 6, 4, 2}]</
{{out}}
<pre>3
7/2</pre>
Custom function:
<
If[Mod[L,2]==0,
(t[[L/2]]+t[[L/2+1]])/2
Line 2,529:
t[[(L+1)/2]]
]
]</
Example of custom function:
<
mymedian[{1, 5, 3, 6, 4, 2}]</
{{out}}
<pre>3
Line 2,539:
=={{header|MATLAB}}==
If the input has an even number of elements, function returns the mean of the middle two values:
<
medianValue = median(setOfValues);
end</
=={{header|Maxima}}==
<
median([41, 56, 72, 17, 93, 44, 32]); /* 44 */
median([41, 72, 17, 93, 44, 32]); /* 85/2 */</
=={{header|MiniScript}}==
<
self.sort
m = floor(self.len/2)
Line 2,557:
print [41, 56, 72, 17, 93, 44, 32].median
print [41, 72, 17, 93, 44, 32].median</
{{out}}
<pre>44
Line 2,563:
=={{header|MUMPS}}==
<
;X is assumed to be a list of numbers separated by "^"
;I is a loop index
Line 2,577:
SET J="" FOR I=1:1:$SELECT(ODD:L\2+1,'ODD:L/2) SET J=$ORDER(Y(J))
QUIT $SELECT(ODD:J,'ODD:(J+$ORDER(Y(J)))/2)
</syntaxhighlight>
<pre>USER>W $$MEDIAN^ROSETTA("-1.3^2.43^3.14^17^2E-3")
3.14
Line 2,589:
=={{header|Nanoquery}}==
{{trans|Python}}
<
def median(aray)
Line 2,600:
println a + " " + median(a)
a = {4.1, 7.2, 1.7, 9.3, 4.4, 3.2}
println a + " " + median(a)</
=={{header|NetRexx}}==
{{trans|Java}}
<
options replace format comments java crossref symbols nobinary
Line 2,668:
if i > j then return +1
else return 0
</syntaxhighlight>
'''Output:'''
<pre>
Line 2,692:
=={{header|NewLISP}}==
<
; oofoe 2012-01-25
Line 2,714:
(test '(3 4 1 -8.4 7.2 4 1 1.2))
(exit)</
Sample output:
Line 2,726:
=={{header|Nim}}==
{{trans|Python}}
<
proc median(xs: seq[float]): float =
Line 2,736:
echo formatFloat(median(a), precision = 0)
a = @[4.1, 7.2, 1.7, 9.3, 4.4, 3.2]
echo formatFloat(median(a), precision = 0)</
Example Output:
Line 2,744:
=={{header|Oberon-2}}==
Oxford Oberon-2
<
MODULE Median;
IMPORT Out;
Line 2,826:
Out.Fixed(Median(ary,0,7),4,2);Out.Ln;
END Median.
</syntaxhighlight>
Output:
<pre>
Line 2,836:
=={{header|Objeck}}==
<
use Structure;
Line 2,868:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
<
let median array =
let len = Array.length array in
Line 2,880:
median a;;
let a = [|4.1; 7.2; 1.7; 9.3; 4.4; 3.2|];;
median a;;</
=={{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.
<
if (numel(v) < 1)
y = NA;
Line 2,904:
disp(median(a))
disp(median2(b)) % 4.25
disp(median(b))</
=={{header|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,944:
-- results for the compares
return (left - right)~sign
</syntaxhighlight>
=={{header|Oz}}==
<
fun {Median Xs}
Len = {Length Xs}
Line 2,959:
in
{Show {Median [4.1 5.6 7.2 1.7 9.3 4.4 3.2]}}
{Show {Median [4.1 7.2 1.7 9.3 4.4 3.2]}}</
=={{header|PARI/GP}}==
Sorting solution.
<
vecsort(v)[#v\2]
};</
Linear-time solution, mostly proof-of-concept but perhaps suitable for large lists.
<
if(#v<15, return(vecsort(v)[k]));
my(u=List(),pivot,left=List(),right=List());
Line 2,988:
BFPRT(left, k)
)
};</
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<
type
Line 3,048:
writeln;
writeln('Median: ', Median(A):7:3);
end.</
Output:
<pre>% ./Median
Line 3,059:
=={{header|Perl}}==
{{trans|Python}}
<
my @a = sort {$a <=> $b} @_;
return ($a[$#a/2] + $a[@a/2]) / 2;
}</
=={{header|Phix}}==
The obvious simple way:
<!--<
<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,080:
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</
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.
<!--<
<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,097:
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span> <span style="color: #000080;font-style:italic;">-- (or perhaps return {s,res})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</
=={{header|Phixmonti}}==
<
def median /# l -- n #/
Line 3,113:
( 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 ) median ?</
=={{header|PHP}}==
This solution uses the sorting method of finding the median.
<
function median($arr)
{
Line 3,135:
echo median(array(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)) . "\n"; // 4.4
echo median(array(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)) . "\n"; // 4.25
</syntaxhighlight>
=={{header|Picat}}==
<
Lists = [
[1.121,10.3223,3.41,12.1,0.01],
Line 3,162:
Len = L.length,
H = Len // 2,
LL = sort(L).</
{{out}}
Line 3,177:
=={{header|PicoLisp}}==
<
(let N (length Lst)
(if (bit? 1 N)
Line 3,188:
(prinl (round (median (1.0 2.0 3.0 4.0))))
(prinl (round (median (5.1 2.6 6.2 8.8 4.6 4.1))))
(prinl (round (median (5.1 2.6 8.8 4.6 4.1))))</
Output:
<pre>2.00
Line 3,196:
=={{header|PL/I}}==
<
n = dimension(A,1);
if iand(n,1) = 1 then /* an odd number of elements */
median = A(n/2);
else /* an even number of elements */
median = (a(n/2) + a(trunc(n/2)+1) )/2;</
=={{header|PowerShell}}==
Line 3,208:
All statistical properties could easily be added to the output object.
<
function Measure-Data
{
Line 3,278:
}
}
</syntaxhighlight>
<
$statistics = Measure-Data 4, 5, 6, 7, 7, 7, 8, 1, 1, 1, 2, 3
$statistics
</syntaxhighlight>
{{Out}}
<pre>
Line 3,296:
</pre>
Median only:
<
$statistics.Median
</syntaxhighlight>
{{Out}}
<pre>
Line 3,305:
=={{header|Processing}}==
<
float[] numbers = {3.1, 4.1, 5.9, 2.6, 5.3, 5.8};
println(median(numbers));
Line 3,316:
float median = (nums[(nums.length - 1) / 2] + nums[nums.length / 2]) / 2.0;
return median;
}</
{{Out}}
<pre>4.7
Line 3,322:
=={{header|Prolog}}==
<
length(L, Length),
I is Length div 2,
Line 3,330:
maplist(nth1, Mid, [S, S], X),
sumlist(X, Y),
Z is Y/2.</
=={{header|Pure}}==
Inspired by the Haskell version.
<
when len = # x;
mid = len div 2;
rem = len mod 2;
end;</
Output:<pre>> median [1, 3, 5];
3.0
Line 3,346:
=={{header|PureBasic}}==
<
If length = 0 : ProcedureReturn 0.0 : EndIf
SortArray(values(), #PB_Sort_Ascending)
Line 3,380:
Data.i 6
Data.d 4.1, 7.2, 1.7, 9.3, 4.4, 3.2
EndDataSection</
=={{header|Python}}==
<
srtd = sorted(aray)
alen = len(srtd)
Line 3,391:
print a, median(a)
a = (4.1, 7.2, 1.7, 9.3, 4.4, 3.2)
print a, median(a)</
=={{header|R}}==
Line 3,397:
{{trans|Octave}}
<
if ( length(v) < 1 )
NA
Line 3,416:
print(omedian(a))
print(median(b)) # 4.25
print(omedian(b))</
=={{header|Racket}}==
<
(define (median numbers)
(define sorted (list->vector (sort (vector->list numbers) <)))
Line 3,432:
(median '#()) ;; #f
(median '#(5 4 2 3)) ;; 7/2
(median '#(3 4 1 -8.4 7.2 4 1 1.2)) ;; 2.1</
=={{header|Raku}}==
Line 3,438:
{{works with|Rakudo|2016.08}}
<
my @a = sort @_;
return (@a[(*-1) div 2] + @a[* div 2]) / 2;
}</
Notes:
Line 3,450:
<br>
In a slightly more compact way:
<
=={{header|REBOL}}==
<
median: func [
"Returns the midpoint value in a series of numbers; half the values are above, half are below."
Line 3,469:
]
]
</syntaxhighlight>
=={{header|ReScript}}==
<
{
let float_compare = (a, b) => {
Line 3,495:
Js.log(median([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]))
Js.log(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]))</
{{out}}
<pre>
Line 3,505:
=={{header|REXX}}==
<
/* ══════════vector════════════ ══show vector═══ ════════show result═══════════ */
v= 1 9 2 4 ; say "vector" v; say 'median──────►' median(v); say
Line 3,528:
n= m + 1 /*N: the next element after M. */
if # // 2 then return @.n /*[odd?] // ◄───REXX's ÷ remainder*/
return (@.m + @.n) / 2 /*process an even─element vector. */</
{{out|output}}
<pre>
Line 3,545:
=={{header|Ring}}==
<
aList = [5,4,2,3]
see "medium : " + median(aList) + nl
Line 3,555:
return (srtd[alen/2] + srtd[alen/2 + 1]) / 2.0
else return srtd[ceil(alen/2)] ok
</syntaxhighlight>
=={{header|Ruby}}==
<
return nil if ary.empty?
mid, rem = ary.length.divmod(2)
Line 3,571:
p median([5,3,4]) # => 4
p median([5,4,2,3]) # => 3.5
p median([3,4,1,-8.4,7.2,4,1,1.2]) # => 2.1</
Alternately:
<
srtd = aray.sort
alen = srtd.length
(srtd[(alen-1)/2] + srtd[alen/2]) / 2.0
end</
=={{header|Run BASIC}}==
<
mem$ = "CREATE TABLE med (x float)"
#mem execute(mem$)
Line 3,610:
print " Median :";median;chr$(9);" Values:";a$
RETURN</
<pre>Median :4.4 Values:4.1,5.6,7.2,1.7,9.3,4.4,3.2
Median :4.25 Values:4.1,7.2,1.7,9.3,4.4,3.2
Line 3,622:
Sorting, then obtaining the median element:
<
// sort in ascending order, panic on f64::NaN
xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );
Line 3,636:
let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.];
println!("{:?}", median(nums))
}</
{{out}}
Line 3,644:
{{works with|Scala|2.8}} (See the Scala discussion on [[Mean]] for more information.)
<
import n._
val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2)
if (s.size % 2 == 0) (lower.last + upper.head) / fromInt(2) else upper.head
}</
This isn't really optimal. The methods <tt>splitAt</tt> and <tt>last</tt> are O(n/2)
Line 3,657:
{{trans|Python}}
Using Rosetta Code's [[Bubble_Sort#Scheme|bubble-sort function]]
<
(* (+ (list-ref (bubble-sort l >) (round (/ (- (length l) 1) 2)))
(list-ref (bubble-sort l >) (round (/ (length l) 2)))) 0.5))</
Using [http://srfi.schemers.org/srfi-95/srfi-95.html SRFI-95]:
<
(* (+ (list-ref (sort l less?) (round (/ (- (length l) 1) 2)))
(list-ref (sort l less?) (round (/ (length l) 2)))) 0.5))</
=={{header|Seed7}}==
<
include "float.s7i";
Line 3,694:
writeln("flist1 median is " <& median(flist1) digits 2 lpad 7); # 4.85
writeln("flist2 median is " <& median(flist2) digits 2 lpad 7); # 4.60
end func;</
=={{header|SenseTalk}}==
SenseTalk has a built-in median function. This example also shows the implementation of a customMedian function that returns the same results.
<
put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]
Line 3,712:
return the middle item of list
end if
end customMedian</
Output:
<
5
4.4
5</
=={{header|Sidef}}==
<
var srtd = arry.sort;
var alen = srtd.length;
srtd[(alen-1)/2]+srtd[alen/2] / 2;
}</
=={{header|Slate}}==
<
[
s isEmpty
Line 3,737:
ifTrue: [(sorted middle + (sorted at: sorted indexMiddle - 1)) / 2]
ifFalse: [sorted middle]]
].</
<
inform: { 4.1 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } median.</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
median [
self size = 0
Line 3,757:
ifTrue: [ ^nil ]
]
].</
<
median displayNl.
{ 4.1 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } asOrderedCollection
median displayNl.</
=={{header|Stata}}==
Use '''[https://www.stata.com/help.cgi?summarize summarize]''' to compute the median of a variable (as well as other basic statistics).
<
gen x=rbeta(0.2,1.3)
quietly summarize x, detail
display r(p50)</
Here is a straightforward implementation using '''[https://www.stata.com/help.cgi? sort]'''.
<
sort `1'
if mod(_N,2)==0 {
Line 3,785:
calcmedian x
display r(p50)</
=={{header|Tcl}}==
<
set list [lsort -real $args]
set len [llength $list]
Line 3,803:
}
puts [median 3.0 4.0 1.0 -8.4 7.2 4.0 1.0 1.2]; # --> 2.1</
=={{header|TI-83 BASIC}}==
Using the built-in function:
<
=={{header|TI-89 BASIC}}==
<
=={{header|Ursala}}==
the simple way (sort first and then look in the middle)
<
#import flo
median = fleq-<; @K30K31X eql?\~&rh div\2.+ plus@lzPrhPX</
test program, once with an odd length and once with an even length vector
<
examples =
Line 3,827:
median~~ (
<9.3,-2.0,4.0,7.3,8.1,4.1,-6.3,4.2,-1.0,-8.4>,
<8.3,-3.6,5.7,2.3,9.3,5.4,-2.3,6.3,9.9>)</
output:
<pre>
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.
<
double a = *(double*) a_ref;
double b = *(double*) b_ref;
Line 3,853:
double[] array2 = {2, 4, 6, 1, 7, 3, 5, 8};
print(@"$(median(array1)) $(median(array2))\n");
}</
=={{header|VBA}}==
{{trans|Phix}}
Uses [[Quickselect_algorithm#VBA|quick select]].
<
Dim res As Double, tmp As Integer
Dim l As Integer, k As Integer
Line 3,875:
s = [{4, 2, 3, 5, 1, 6}]
Debug.Print medianq(s)
End Sub</
<pre> 3,5 </pre>
Line 3,884:
The result is returned in text register @10. In case of even number of items, the lower middle value is returned.
<
EOF Goto_Line(Cur_Line/2)
Reg_Copy(10, 1)</
=={{header|Vlang}}==
<
println(median([3, 1, 4, 1])) // prints 2
println(median([3, 1, 4, 1, 5])) // prints 3
Line 3,903:
}
return m
}</
{{out}}
Line 3,915:
println(stats.median<int>([1, 1, 3, 4])) // prints 2
println(stats.median<int>([1, 1, 3, 4, 5])) // prints 3
}</
=={{header|Wortel}}==
<
; iterative
med1 &l @let {a @sort l s #a i @/s 2 ?{%%s 2 ~/ 2 +`-i 1 a `i a `i a}}
Line 3,931:
!med2 [4 5 2 1]
]]
}</
Returns: <pre>[2 3 2 3]</pre>
Line 3,938:
{{libheader|Wren-math}}
{{libheader|Wren-queue}}
<
import "/math" for Nums
import "/queue" for PriorityQueue
Line 3,969:
}
System.print()
}</
{{out}}
Line 3,984:
=={{header|Yabasic}}==
{{trans|Lua}}
<
return int(x + .05)
end sub
Line 4,040:
print median("4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2") // 4.4
print median("4.1, 7.2, 1.7, 9.3, 4.4, 3.2") // 4.25
</syntaxhighlight>
=={{header|zkl}}==
Using the [[Quickselect algorithm#zkl]] for O(n) time:
<
fcn median(xs){
Line 4,050:
if (n.isOdd) return(quickSelect(xs,n/2));
( quickSelect(xs,n/2-1) + quickSelect(xs,n/2) )/2;
}</
<
median(T( 5.1, 2.6, 8.8, 4.6, 4.1 )); //-->4.6</
=={{header|Zoea}}==
<
program: median
case: 1
Line 4,066:
input: [2,5,6,8]
output: 5.5
</syntaxhighlight>
=={{header|Zoea Visual}}==
Line 4,072:
=={{header|zonnon}}==
<
module Averages;
Line 4,142:
writeln(Median(ary):10:2)
end Averages.
</syntaxhighlight>
<pre>
4
|