Averages/Median: Difference between revisions
Content added Content deleted
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 20: | Line 20: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=11l>F median(aray) |
||
V srtd = sorted(aray) |
V srtd = sorted(aray) |
||
V alen = srtd.len |
V alen = srtd.len |
||
Line 26: | Line 26: | ||
print(median([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2])) |
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]))</ |
print(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 36: | Line 36: | ||
{{libheader|Action! Tool Kit}} |
{{libheader|Action! Tool Kit}} |
||
{{libheader|Action! Real Math}} |
{{libheader|Action! Real Math}} |
||
< |
<syntaxhighlight lang=Action!>INCLUDE "H6:REALMATH.ACT" |
||
DEFINE PTR="CARD" |
DEFINE PTR="CARD" |
||
Line 103: | Line 103: | ||
Test(a,i) |
Test(a,i) |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Averages_Median.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Averages_Median.png Screenshot from Atari 8-bit computer] |
||
Line 118: | Line 118: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang=ada>with Ada.Text_IO, Ada.Float_Text_IO; |
||
procedure FindMedian is |
procedure FindMedian is |
||
Line 148: | Line 148: | ||
Ada.Float_Text_IO.Put( median_val ); |
Ada.Float_Text_IO.Put( median_val ); |
||
Ada.Text_IO.New_line; |
Ada.Text_IO.New_line; |
||
end FindMedian;</ |
end FindMedian;</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{trans|C}}< |
{{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 215: | Line 215: | ||
"<: ", whole (less,0), new line, |
"<: ", whole (less,0), new line, |
||
">: ", whole (more, 0), new line, |
">: ", whole (more, 0), new line, |
||
"=: ", whole (eq, 0), new line))</ |
"=: ", whole (eq, 0), new line))</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre>length: 97738 |
<pre>length: 97738 |
||
Line 226: | Line 226: | ||
=={{header|AntLang}}== |
=={{header|AntLang}}== |
||
AntLang has a built-in median function. |
AntLang has a built-in median function. |
||
<lang |
<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> |
||
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: <lang |
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> |
||
⎕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]} |
||
</syntaxhighlight> |
|||
</lang> |
|||
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: |
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: | Line 276: | ||
=={{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} |
||
set med to medi(alist) |
set med to medi(alist) |
||
Line 319: | Line 319: | ||
return max |
return max |
||
end findmax</ |
end findmax</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
<lang |
<syntaxhighlight lang=applescript>4.5</syntaxhighlight> |
||
===Composing functionally=== |
===Composing functionally=== |
||
Line 328: | Line 328: | ||
{{Trans|JavaScript}} |
{{Trans|JavaScript}} |
||
{{Trans|Haskell}} |
{{Trans|Haskell}} |
||
< |
<syntaxhighlight lang=AppleScript>-- MEDIAN --------------------------------------------------------------------- |
||
-- median :: [Num] -> Num |
-- median :: [Num] -> Num |
||
Line 433: | Line 433: | ||
missing value |
missing value |
||
end if |
end if |
||
end uncons</ |
end uncons</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<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. |
||
on getMedian(theList, l, r) |
on getMedian(theList, l, r) |
||
if (theList is {}) then return theList |
if (theList is {}) then return theList |
||
Line 512: | Line 512: | ||
set end of testList to (random number 500) / 5 |
set end of testList to (random number 500) / 5 |
||
end repeat |
end repeat |
||
return {|numbers|:testList, median:getMedian(testList, 1, (count testList))}</ |
return {|numbers|:testList, median:getMedian(testList, 1, (count testList))}</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
<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. |
||
on getMedian(theList, l, r) |
on getMedian(theList, l, r) |
||
script o |
script o |
||
Line 579: | Line 579: | ||
end repeat |
end repeat |
||
return {|numbers|:testList, median:getMedian(testList, 1, (count testList))} |
return {|numbers|:testList, median:getMedian(testList, 1, (count testList))} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{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> |
||
=={{header|Applesoft BASIC}}== |
=={{header|Applesoft BASIC}}== |
||
< |
<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 609: | ||
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</ |
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</ |
? R</syntaxhighlight>Output:<pre>5.95</pre> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<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] |
||
print median arr |
print median arr |
||
print median arr2</ |
print median arr2</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 628: | Line 628: | ||
=={{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 |
||
MsgBox % median(seq, "`,") ; 4.1 |
MsgBox % median(seq, "`,") ; 4.1 |
||
Line 637: | Line 637: | ||
median := Floor(seq0 / 2) |
median := Floor(seq0 / 2) |
||
Return seq%median% |
Return seq%median% |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Line 643: | Line 643: | ||
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 |
||
BEGIN { |
BEGIN { |
||
Line 689: | Line 689: | ||
print "" |
print "" |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example output: |
Example output: |
||
Line 697: | Line 697: | ||
=={{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 |
||
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 708: | Line 708: | ||
SORT b |
SORT b |
||
PRINT "Median of b: ", Median(b)</ |
PRINT "Median of b: ", Median(b)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 726: | 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>. |
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 |
DIM vec1(10) AS SINGLE, vec2(11) AS SINGLE, n AS INTEGER |
||
Line 755: | Line 755: | ||
median = (v(INT((ub + lb) / 2)) + v(INT((ub + lb) / 2) + 1)) / 2 |
median = (v(INT((ub + lb) / 2)) + v(INT((ub + lb) / 2) + 1)) / 2 |
||
END IF |
END IF |
||
END FUNCTION</ |
END FUNCTION</syntaxhighlight> |
||
See also: [[#BBC BASIC|BBC BASIC]], [[#Liberty BASIC|Liberty BASIC]], [[#PureBasic|PureBasic]], [[#TI-83 BASIC|TI-83 BASIC]], [[#TI-89 BASIC|TI-89 BASIC]]. |
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: | Line 761: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang=bbcbasic> INSTALL @lib$+"SORTLIB" |
||
Sort% = FN_sortinit(0,0) |
Sort% = FN_sortinit(0,0) |
||
Line 777: | Line 777: | ||
CALL Sort%, a(0) |
CALL Sort%, a(0) |
||
= (a(C% DIV 2) + a((C%-1) DIV 2)) / 2 |
= (a(C% DIV 2) + a((C%-1) DIV 2)) / 2 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre>Median of a() is 4.4 |
<pre>Median of a() is 4.4 |
||
Line 794: | 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. |
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 |
begin decimals end int list med med1 med2 num number |
||
. 0:?list |
. 0:?list |
||
Line 818: | Line 818: | ||
) |
) |
||
& !med |
& !med |
||
);</ |
);</syntaxhighlight> |
||
Line 834: | Line 834: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang=C>#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 864: | Line 864: | ||
printf("flist2 median is %7.2f\n", median(&flist2)); /* 4.60 */ |
printf("flist2 median is %7.2f\n", median(&flist2)); /* 4.60 */ |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
===Quickselect algorithm=== |
===Quickselect algorithm=== |
||
Average O(n) time: |
Average O(n) time: |
||
< |
<syntaxhighlight lang=c>#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <time.h> |
#include <time.h> |
||
Line 946: | Line 946: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
< |
<syntaxhighlight lang=c>length: 992021 |
||
median: 0.000473 |
median: 0.000473 |
||
<: 496010 |
<: 496010 |
||
>: 496010 |
>: 496010 |
||
=: 1</ |
=: 1</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang=csharp>using System; |
||
using System.Linq; |
using System.Linq; |
||
Line 989: | Line 989: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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> |
||
// inputs must be random-access iterators of doubles |
// inputs must be random-access iterators of doubles |
||
Line 1,024: | Line 1,024: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
===Order Statistic Tree=== |
===Order Statistic Tree=== |
||
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> |
||
#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,068: | Line 1,068: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
Simple: |
Simple: |
||
< |
<syntaxhighlight lang=lisp>(defn median [ns] |
||
(let [ns (sort ns) |
(let [ns (sort ns) |
||
cnt (count ns) |
cnt (count ns) |
||
Line 1,078: | Line 1,078: | ||
(if (odd? cnt) |
(if (odd? cnt) |
||
(nth ns mid) |
(nth ns mid) |
||
(/ (+ (nth ns mid) (nth ns (dec mid))) 2))))</ |
(/ (+ (nth ns mid) (nth ns (dec mid))) 2))))</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
Intrinsic function: |
Intrinsic function: |
||
< |
<syntaxhighlight lang=cobol>FUNCTION MEDIAN(some-table (ALL))</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 1,088: | Line 1,088: | ||
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) |
||
"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,110: | Line 1,110: | ||
(defun median (list predicate) |
(defun median (list predicate) |
||
(select-nth (floor (length list) 2) list predicate))</ |
(select-nth (floor (length list) 2) list predicate))</syntaxhighlight> |
||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
< |
<syntaxhighlight lang=ruby>def median(ary) |
||
srtd = ary.sort |
srtd = ary.sort |
||
alen = srtd.size |
alen = srtd.size |
||
Line 1,127: | Line 1,127: | ||
a = [5.0] |
a = [5.0] |
||
puts median a |
puts median a |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,137: | Line 1,137: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang=d>import std.stdio, std.algorithm; |
||
T median(T)(T[] nums) pure nothrow { |
T median(T)(T[] nums) pure nothrow { |
||
Line 1,153: | Line 1,153: | ||
auto a2 = [5.1, 2.6, 8.8, 4.6, 4.1]; |
auto a2 = [5.1, 2.6, 8.8, 4.6, 4.1]; |
||
writeln("Odd median: ", a2.median); |
writeln("Odd median: ", a2.median); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Even median: 4.85 |
<pre>Even median: 4.85 |
||
Line 1,159: | Line 1,159: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang=Delphi>program AveragesMedian; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 1,181: | 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, 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))); |
Writeln(Median(TDoubleDynArray.Create(4.1, 7.2, 1.7, 9.3, 4.4, 3.2))); |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
Line 1,187: | Line 1,187: | ||
TODO: Use the selection algorithm, whatever that is [[Category:E examples needing attention]] |
TODO: Use the selection algorithm, whatever that is [[Category:E examples needing attention]] |
||
< |
<syntaxhighlight lang=e>def median(list) { |
||
def sorted := list.sort() |
def sorted := list.sort() |
||
def count := sorted.size() |
def count := sorted.size() |
||
Line 1,197: | Line 1,197: | ||
return (sorted[mid1] + sorted[mid2]) / 2 |
return (sorted[mid1] + sorted[mid2]) / 2 |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang=e>? median([1,9,2]) |
||
# value: 2 |
# value: 2 |
||
? median([1,9,2,4]) |
? median([1,9,2,4]) |
||
# value: 3.0</ |
# value: 3.0</syntaxhighlight> |
||
=={{header|EasyLang}}== |
=={{header|EasyLang}}== |
||
Line 1,247: | Line 1,247: | ||
test[] = [ 4.1 7.2 1.7 9.3 4.4 3.2 ] |
test[] = [ 4.1 7.2 1.7 9.3 4.4 3.2 ] |
||
call median test[] med |
call median test[] med |
||
print med</ |
print med</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 1,255: | Line 1,255: | ||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<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,271: | Line 1,271: | ||
(median (iota 10001)) |
(median (iota 10001)) |
||
→ 5000 |
→ 5000 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 5.0 : |
ELENA 5.0 : |
||
< |
<syntaxhighlight lang=elena>import system'routines; |
||
import system'math; |
import system'math; |
||
import extensions; |
import extensions; |
||
Line 1,314: | Line 1,314: | ||
console.readChar() |
console.readChar() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,323: | Line 1,323: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
{{trans|Erlang}} |
{{trans|Erlang}} |
||
< |
<syntaxhighlight lang=elixir>defmodule Average do |
||
def median([]), do: nil |
def median([]), do: nil |
||
def median(list) do |
def median(list) do |
||
Line 1,338: | Line 1,338: | ||
Enum.each(1..6, fn i -> |
Enum.each(1..6, fn i -> |
||
(for _ <- 1..i, do: :rand.uniform(6)) |> median.() |
(for _ <- 1..i, do: :rand.uniform(6)) |> median.() |
||
end)</ |
end)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,352: | Line 1,352: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<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,415: | Line 1,415: | ||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
Line 1,455: | Line 1,455: | ||
PRINT(R) |
PRINT(R) |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
Ouput is 5.95 |
Ouput is 5.95 |
||
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> |
||
>type median |
>type median |
||
function median (x, v: none, p) |
function median (x, v: none, p) |
||
Line 1,515: | Line 1,515: | ||
>0.2*10+0.8*1 |
>0.2*10+0.8*1 |
||
2.8 |
2.8 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<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,542: | Line 1,542: | ||
end function |
end function |
||
? median({ 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5 })</ |
? median({ 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5 })</syntaxhighlight> |
||
Output: |
Output: |
||
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> |
||
=MEDIAN(A1:A10) |
=MEDIAN(A1:A10) |
||
</syntaxhighlight> |
|||
</lang> |
|||
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> |
||
=MEDIAN( |
=MEDIAN( |
||
</syntaxhighlight> |
|||
</lang> |
|||
and then select the start and end cells, not necessarily in the same row or column. |
and then select the start and end cells, not necessarily in the same row or column. |
||
Line 1,575: | Line 1,575: | ||
9 |
9 |
||
0 |
0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
Median of Medians algorithm implementation |
Median of Medians algorithm implementation |
||
< |
<syntaxhighlight lang=fsharp> |
||
let rec splitToFives list = |
let rec splitToFives list = |
||
match list with |
match list with |
||
Line 1,624: | Line 1,624: | ||
let z' = [1.;5.;2.;8.;7.] |
let z' = [1.;5.;2.;8.;7.] |
||
start z' |
start z' |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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 ; |
||
IN: median |
IN: median |
||
Line 1,654: | Line 1,654: | ||
: median ( seq -- median ) |
: median ( seq -- median ) |
||
dup length 1 - 2 / floor nth-in-order ;</ |
dup length 1 - 2 / floor nth-in-order ;</syntaxhighlight> |
||
Usage: |
Usage: |
||
< |
<syntaxhighlight lang=factor>( scratchpad ) 11 iota median . |
||
5 |
5 |
||
( scratchpad ) 10 iota median . |
( scratchpad ) 10 iota median . |
||
4</ |
4</syntaxhighlight> |
||
=={{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 |
||
: cell- -cell + ; |
: cell- -cell + ; |
||
Line 1,693: | Line 1,693: | ||
: median ( array len -- m ) |
: median ( array len -- m ) |
||
1- cells over + 2dup mid to midpoint |
1- cells over + 2dup mid to midpoint |
||
select midpoint @ ;</ |
select midpoint @ ;</syntaxhighlight> |
||
< |
<syntaxhighlight lang=forth>create test 4 , 2 , 1 , 3 , 5 , |
||
test 4 median . \ 2 |
test 4 median . \ 2 |
||
test 5 median . \ 3</ |
test 5 median . \ 3</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{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 /), & |
real :: a(7) = (/ 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 /), & |
||
Line 1,744: | Line 1,744: | ||
end function median |
end function median |
||
end program Median_Test</ |
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, < |
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 </ |
IF (MOD(N,2).EQ.0) MEDIAN = (FINDELEMENT(K,A,N) + MEDIAN)/2 </syntaxhighlight> |
||
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). |
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}}== |
=={{header|FreeBASIC}}== |
||
< |
<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,797: | Line 1,797: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,806: | Line 1,806: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang=gap>Median := function(v) |
||
local n, w; |
local n, w; |
||
w := SortedList(v); |
w := SortedList(v); |
||
Line 1,819: | Line 1,819: | ||
# 44 |
# 44 |
||
Median(b); |
Median(b); |
||
# 85/2</ |
# 85/2</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
===Sort=== |
===Sort=== |
||
Go built-in sort. O(n log n). |
Go built-in sort. O(n log n). |
||
< |
<syntaxhighlight lang=go>package main |
||
import ( |
import ( |
||
Line 1,844: | Line 1,844: | ||
} |
} |
||
return m |
return m |
||
}</ |
}</syntaxhighlight> |
||
===Partial selection sort=== |
===Partial selection sort=== |
||
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 |
||
import "fmt" |
import "fmt" |
||
Line 1,880: | Line 1,880: | ||
} |
} |
||
return list[k] |
return list[k] |
||
}</ |
}</syntaxhighlight> |
||
===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 |
||
import ( |
import ( |
||
Line 1,934: | Line 1,934: | ||
} |
} |
||
return a[0] |
return a[0] |
||
}</ |
}</syntaxhighlight> |
||
=={{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) { |
||
def s = col as SortedSet |
def s = col as SortedSet |
||
if (s == null) return null |
if (s == null) return null |
||
Line 1,946: | Line 1,946: | ||
def l = s.collect { it } |
def l = s.collect { it } |
||
n%2 == 1 ? l[m] : (l[m] + l[m-1])/2 |
n%2 == 1 ? l[m] : (l[m] + l[m-1])/2 |
||
}</ |
}</syntaxhighlight> |
||
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] |
||
def sz = a.size() |
def sz = a.size() |
||
Line 1,955: | Line 1,955: | ||
println """${median(a[0..<(sz-it)])} == median(${a[0..<(sz-it)]}) |
println """${median(a[0..<(sz-it)])} == median(${a[0..<(sz-it)]}) |
||
${median(a[it..<sz])} == median(${a[it..<sz]})""" |
${median(a[it..<sz])} == median(${a[it..<sz]})""" |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
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) |
||
nth :: Ord t => [t] -> Int -> t |
nth :: Ord t => [t] -> Int -> t |
||
Line 2,009: | Line 2,009: | ||
[[], [7], [5, 3, 4], [5, 4, 2, 3], [3, 4, 1, -8.4, 7.2, 4, 1, 1.2]] |
[[], [7], [5, 3, 4], [5, 4, 2, 3], [3, 4, 1, -8.4, 7.2, 4, 1, 1.2]] |
||
where |
where |
||
printMay = maybe (putStrLn "(not defined)") print</ |
printMay = maybe (putStrLn "(not defined)") print</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>(not defined) |
<pre>(not defined) |
||
Line 2,019: | Line 2,019: | ||
Or {{libheader|hstats}} |
Or {{libheader|hstats}} |
||
< |
<syntaxhighlight lang=haskell>> Math.Statistics.median [1,9,2,4] |
||
3.0</ |
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) |
||
vec = RAN(1) |
vec = RAN(1) |
||
Line 2,033: | Line 2,033: | ||
ELSE |
ELSE |
||
median = ( vec(n/2) + vec(n/2 + 1) ) / 2 |
median = ( vec(n/2) + vec(n/2 + 1) ) / 2 |
||
ENDIF</ |
ENDIF</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Line 2,046: | Line 2,046: | ||
return if n % 2 = 1 then A[n/2+1] |
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 |
else (A[n/2]+A[n/2+1])/2.0 | 0 # 0 if empty list |
||
end</ |
end</syntaxhighlight> |
||
Sample outputs: |
Sample outputs: |
||
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' |
||
median 1 9 2 4 |
median 1 9 2 4 |
||
3</ |
3</syntaxhighlight> |
||
The definition given in the addon script is: |
The definition given in the addon script is: |
||
< |
<syntaxhighlight lang=j>midpt=: -:@<:@# |
||
median=: -:@(+/)@((<. , >.)@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: |
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 |
median 1 9 2 4 |
||
2 4</ |
2 4</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
Line 2,073: | Line 2,073: | ||
Sorting: |
Sorting: |
||
< |
<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); |
||
return (list.get(list.size() / 2) + list.get((list.size() - 1) / 2)) / 2; |
return (list.get(list.size() / 2) + list.get((list.size() - 1) / 2)) / 2; |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
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) { |
||
PriorityQueue<Double> pq = new PriorityQueue<Double>(list); |
PriorityQueue<Double> pq = new PriorityQueue<Double>(list); |
||
int n = list.size(); |
int n = list.size(); |
||
Line 2,091: | Line 2,091: | ||
else |
else |
||
return (pq.poll() + pq.poll()) / 2.0; |
return (pq.poll() + pq.poll()) / 2.0; |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Java|1.8+}} |
{{works with|Java|1.8+}} |
||
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> |
||
@FunctionalInterface |
@FunctionalInterface |
||
interface MedianFinder<T, R> extends Function<Collection<T>, R> { |
interface MedianFinder<T, R> extends Function<Collection<T>, R> { |
||
Line 2,148: | Line 2,148: | ||
public static BigDecimal bigDecimals(Collection<BigDecimal> bigDecimalCollection) { return BIG_DECIMALS.apply(bigDecimalCollection); } |
public static BigDecimal bigDecimals(Collection<BigDecimal> bigDecimalCollection) { return BIG_DECIMALS.apply(bigDecimalCollection); } |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES5=== |
===ES5=== |
||
< |
<syntaxhighlight lang=javascript>function median(ary) { |
||
if (ary.length == 0) |
if (ary.length == 0) |
||
return null; |
return null; |
||
Line 2,167: | Line 2,167: | ||
median([5,3,4]); // 4 |
median([5,3,4]); // 4 |
||
median([5,4,2,3]); // 3.5 |
median([5,4,2,3]); // 3.5 |
||
median([3,4,1,-8.4,7.2,4,1,1.2]); // 2.1</ |
median([3,4,1,-8.4,7.2,4,1,1.2]); // 2.1</syntaxhighlight> |
||
===ES6=== |
===ES6=== |
||
Line 2,174: | Line 2,174: | ||
{{Trans|Haskell}} |
{{Trans|Haskell}} |
||
< |
<syntaxhighlight lang=JavaScript>(() => { |
||
'use strict'; |
'use strict'; |
||
Line 2,225: | Line 2,225: | ||
[3, 4, 1, -8.4, 7.2, 4, 1, 1.2] |
[3, 4, 1, -8.4, 7.2, 4, 1, 1.2] |
||
].map(median); |
].map(median); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang=JavaScript>[ |
||
null, |
null, |
||
4, |
4, |
||
3.5, |
3.5, |
||
2.1 |
2.1 |
||
]</ |
]</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
< |
<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 ;</ |
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]</ |
[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</ |
4.25</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Julia has a built-in median() function |
Julia has a built-in median() function |
||
< |
<syntaxhighlight lang=julia>using Statistics |
||
function median2(n) |
function median2(n) |
||
s = sort(n) |
s = sort(n) |
||
Line 2,266: | Line 2,266: | ||
b = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2] |
b = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2] |
||
@show a b median2(a) median(a) median2(b) median(b) </ |
@show a b median2(a) median(a) median2(b) median(b) </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,279: | Line 2,279: | ||
=={{header|K}}== |
=={{header|K}}== |
||
<syntaxhighlight lang=k> |
|||
<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,288: | Line 2,288: | ||
med[1_ v] |
med[1_ v] |
||
2.281911 |
2.281911 |
||
</syntaxhighlight> |
|||
</lang> |
|||
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> |
|||
<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]} |
||
med[v] |
med[v] |
||
2.2819 4.8547 |
2.2819 4.8547 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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 } |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 2,306: | Line 2,306: | ||
median(listOf(5.0, 4.0, 2.0, 3.0)).let { println(it) } // 3.5 |
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 |
median(listOf(3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2)).let { println(it) } // 2.1 |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
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) => { |
||
#a->sort |
#a->sort |
||
Line 2,327: | Line 2,327: | ||
median_ext(array(3,2,7,6)) // 4.5 |
median_ext(array(3,2,7,6)) // 4.5 |
||
median_ext(array(3,2,9,7,6)) // 6</ |
median_ext(array(3,2,9,7,6)) // 6</syntaxhighlight> |
||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<syntaxhighlight lang=lb> |
|||
<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,375: | Line 2,375: | ||
if middle <>intmiddle then median= a( 1 +intmiddle) else median =( a( intmiddle) +a( intmiddle +1)) /2 |
if middle <>intmiddle then median= a( 1 +intmiddle) else median =( a( intmiddle) +a( intmiddle +1)) /2 |
||
end function |
end function |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
4.1 5.6 7.2 1.7 9.3 4.4 3.2 |
4.1 5.6 7.2 1.7 9.3 4.4 3.2 |
||
Line 2,397: | Line 2,397: | ||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<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,405: | Line 2,405: | ||
return (numlist[numlist.count/2]+numlist[numlist.count/2+1])/2.0 |
return (numlist[numlist.count/2]+numlist[numlist.count/2+1])/2.0 |
||
end if |
end if |
||
end</ |
end</syntaxhighlight> |
||
=={{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") |
||
returns 4.4, 4.25</ |
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 |
||
if n < 0 then |
if n < 0 then |
||
return (trunc(n) - 1) |
return (trunc(n) - 1) |
||
Line 2,437: | Line 2,437: | ||
returns the same as the built-in median, viz. |
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") |
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</ |
4.4,4.25</syntaxhighlight> |
||
=={{header|LSL}}== |
=={{header|LSL}}== |
||
< |
<syntaxhighlight lang=LSL>integer MAX_ELEMENTS = 10; |
||
integer MAX_VALUE = 100; |
integer MAX_VALUE = 100; |
||
default { |
default { |
||
Line 2,461: | Line 2,461: | ||
llOwnerSay(" Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst)); |
llOwnerSay(" Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,478: | Line 2,478: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<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,486: | Line 2,486: | ||
print(median({4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2})) |
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}))</ |
print(median({4.1, 7.2, 1.7, 9.3, 4.4, 3.2}))</syntaxhighlight> |
||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
=== 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> |
||
> Statistics:-Median( [ 1, 5, 3, 2, 4 ] ); |
> Statistics:-Median( [ 1, 5, 3, 2, 4 ] ); |
||
3. |
3. |
||
Line 2,497: | Line 2,497: | ||
> Statistics:-Median( [ 1, 5, 3, 6, 2, 4 ] ); |
> Statistics:-Median( [ 1, 5, 3, 6, 2, 4 ] ); |
||
3.50000000000000 |
3.50000000000000 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== 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> |
||
median1 := proc() |
median1 := proc() |
||
local L := sort( [ args ] ); |
local L := sort( [ args ] ); |
||
( L[ iquo( 1 + nargs, 2 ) ] + L[ 1 + iquo( nargs, 2 ) ] ) / 2 |
( L[ iquo( 1 + nargs, 2 ) ] + L[ 1 + iquo( nargs, 2 ) ] ) / 2 |
||
end proc: |
end proc: |
||
</syntaxhighlight> |
|||
</lang> |
|||
For example: |
For example: |
||
< |
<syntaxhighlight lang=Maple> |
||
> median1( 1, 5, 3, 2, 4 ); # 3 |
> median1( 1, 5, 3, 2, 4 ); # 3 |
||
3 |
3 |
||
Line 2,513: | Line 2,513: | ||
> median1( 1, 5, 3, 6, 4, 2 ); # 7/2 |
> median1( 1, 5, 3, 6, 4, 2 ); # 7/2 |
||
7/2 |
7/2 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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}] |
||
Median[{1, 5, 3, 6, 4, 2}]</ |
Median[{1, 5, 3, 6, 4, 2}]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>3 |
<pre>3 |
||
7/2</pre> |
7/2</pre> |
||
Custom function: |
Custom function: |
||
< |
<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,529: | Line 2,529: | ||
t[[(L+1)/2]] |
t[[(L+1)/2]] |
||
] |
] |
||
]</ |
]</syntaxhighlight> |
||
Example of custom function: |
Example of custom function: |
||
< |
<syntaxhighlight lang=Mathematica>mymedian[{1, 5, 3, 2, 4}] |
||
mymedian[{1, 5, 3, 6, 4, 2}]</ |
mymedian[{1, 5, 3, 6, 4, 2}]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>3 |
<pre>3 |
||
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) |
||
medianValue = median(setOfValues); |
medianValue = median(setOfValues); |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<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 */</ |
median([41, 72, 17, 93, 44, 32]); /* 85/2 */</syntaxhighlight> |
||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang=MiniScript>list.median = function() |
||
self.sort |
self.sort |
||
m = floor(self.len/2) |
m = floor(self.len/2) |
||
Line 2,557: | Line 2,557: | ||
print [41, 56, 72, 17, 93, 44, 32].median |
print [41, 56, 72, 17, 93, 44, 32].median |
||
print [41, 72, 17, 93, 44, 32].median</ |
print [41, 72, 17, 93, 44, 32].median</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>44 |
<pre>44 |
||
Line 2,563: | Line 2,563: | ||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
< |
<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,577: | Line 2,577: | ||
SET J="" FOR I=1:1:$SELECT(ODD:L\2+1,'ODD:L/2) SET J=$ORDER(Y(J)) |
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) |
QUIT $SELECT(ODD:J,'ODD:(J+$ORDER(Y(J)))/2) |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre>USER>W $$MEDIAN^ROSETTA("-1.3^2.43^3.14^17^2E-3") |
<pre>USER>W $$MEDIAN^ROSETTA("-1.3^2.43^3.14^17^2E-3") |
||
3.14 |
3.14 |
||
Line 2,589: | Line 2,589: | ||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=Nanoquery>import sort |
||
def median(aray) |
def median(aray) |
||
Line 2,600: | Line 2,600: | ||
println a + " " + median(a) |
println a + " " + median(a) |
||
a = {4.1, 7.2, 1.7, 9.3, 4.4, 3.2} |
a = {4.1, 7.2, 1.7, 9.3, 4.4, 3.2} |
||
println a + " " + median(a)</ |
println a + " " + median(a)</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang=NetRexx>/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 2,668: | Line 2,668: | ||
if i > j then return +1 |
if i > j then return +1 |
||
else return 0 |
else return 0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Output:''' |
'''Output:''' |
||
<pre> |
<pre> |
||
Line 2,692: | Line 2,692: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang=NewLISP>; median.lsp |
||
; oofoe 2012-01-25 |
; oofoe 2012-01-25 |
||
Line 2,714: | Line 2,714: | ||
(test '(3 4 1 -8.4 7.2 4 1 1.2)) |
(test '(3 4 1 -8.4 7.2 4 1 1.2)) |
||
(exit)</ |
(exit)</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 2,726: | Line 2,726: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=nim>import algorithm, strutils |
||
proc median(xs: seq[float]): float = |
proc median(xs: seq[float]): float = |
||
Line 2,736: | Line 2,736: | ||
echo formatFloat(median(a), precision = 0) |
echo formatFloat(median(a), precision = 0) |
||
a = @[4.1, 7.2, 1.7, 9.3, 4.4, 3.2] |
a = @[4.1, 7.2, 1.7, 9.3, 4.4, 3.2] |
||
echo formatFloat(median(a), precision = 0)</ |
echo formatFloat(median(a), precision = 0)</syntaxhighlight> |
||
Example Output: |
Example Output: |
||
Line 2,744: | Line 2,744: | ||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
Oxford Oberon-2 |
Oxford Oberon-2 |
||
< |
<syntaxhighlight lang=oberon2> |
||
MODULE Median; |
MODULE Median; |
||
IMPORT Out; |
IMPORT Out; |
||
Line 2,826: | Line 2,826: | ||
Out.Fixed(Median(ary,0,7),4,2);Out.Ln; |
Out.Fixed(Median(ary,0,7),4,2);Out.Ln; |
||
END Median. |
END Median. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,836: | Line 2,836: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang=objeck> |
||
use Structure; |
use Structure; |
||
Line 2,868: | Line 2,868: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<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,880: | Line 2,880: | ||
median a;; |
median a;; |
||
let a = [|4.1; 7.2; 1.7; 9.3; 4.4; 3.2|];; |
let a = [|4.1; 7.2; 1.7; 9.3; 4.4; 3.2|];; |
||
median a;;</ |
median a;;</syntaxhighlight> |
||
=={{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) |
||
if (numel(v) < 1) |
if (numel(v) < 1) |
||
y = NA; |
y = NA; |
||
Line 2,904: | Line 2,904: | ||
disp(median(a)) |
disp(median(a)) |
||
disp(median2(b)) % 4.25 |
disp(median2(b)) % 4.25 |
||
disp(median(b))</ |
disp(median(b))</syntaxhighlight> |
||
=={{header|ooRexx}}== |
=={{header|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,944: | Line 2,944: | ||
-- results for the compares |
-- results for the compares |
||
return (left - right)~sign |
return (left - right)~sign |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang=oz>declare |
||
fun {Median Xs} |
fun {Median Xs} |
||
Len = {Length Xs} |
Len = {Length Xs} |
||
Line 2,959: | Line 2,959: | ||
in |
in |
||
{Show {Median [4.1 5.6 7.2 1.7 9.3 4.4 3.2]}} |
{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]}}</ |
{Show {Median [4.1 7.2 1.7 9.3 4.4 3.2]}}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Sorting solution. |
Sorting solution. |
||
< |
<syntaxhighlight lang=parigp>median(v)={ |
||
vecsort(v)[#v\2] |
vecsort(v)[#v\2] |
||
};</ |
};</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)={ |
||
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,988: | Line 2,988: | ||
BFPRT(left, k) |
BFPRT(left, k) |
||
) |
) |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
{{works with|Free_Pascal}} |
{{works with|Free_Pascal}} |
||
< |
<syntaxhighlight lang=pascal>Program AveragesMedian(output); |
||
type |
type |
||
Line 3,048: | Line 3,048: | ||
writeln; |
writeln; |
||
writeln('Median: ', Median(A):7:3); |
writeln('Median: ', Median(A):7:3); |
||
end.</ |
end.</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>% ./Median |
<pre>% ./Median |
||
Line 3,059: | Line 3,059: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<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; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
The obvious simple way: |
The obvious simple way: |
||
<!--< |
<!--<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,080: | Line 3,080: | ||
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span> |
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span> |
||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
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)--> |
||
<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,097: | 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;">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> |
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang=Phixmonti>include ..\Utilitys.pmt |
||
def median /# l -- n #/ |
def median /# l -- n #/ |
||
Line 3,113: | Line 3,113: | ||
( 4.1 5.6 7.2 1.7 9.3 4.4 3.2 ) 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 ) median ?</ |
( 4.1 7.2 1.7 9.3 4.4 3.2 ) median ?</syntaxhighlight> |
||
=={{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> |
||
function median($arr) |
function median($arr) |
||
{ |
{ |
||
Line 3,135: | 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, 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 |
echo median(array(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)) . "\n"; // 4.25 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
< |
<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,162: | Line 3,162: | ||
Len = L.length, |
Len = L.length, |
||
H = Len // 2, |
H = Len // 2, |
||
LL = sort(L).</ |
LL = sort(L).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,177: | Line 3,177: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang=PicoLisp>(de median (Lst) |
||
(let N (length Lst) |
(let N (length Lst) |
||
(if (bit? 1 N) |
(if (bit? 1 N) |
||
Line 3,188: | Line 3,188: | ||
(prinl (round (median (1.0 2.0 3.0 4.0)))) |
(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 6.2 8.8 4.6 4.1)))) |
||
(prinl (round (median (5.1 2.6 8.8 4.6 4.1))))</ |
(prinl (round (median (5.1 2.6 8.8 4.6 4.1))))</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>2.00 |
<pre>2.00 |
||
Line 3,196: | Line 3,196: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<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 */ |
||
median = A(n/2); |
median = A(n/2); |
||
else /* an even number of elements */ |
else /* an even number of elements */ |
||
median = (a(n/2) + a(trunc(n/2)+1) )/2;</ |
median = (a(n/2) + a(trunc(n/2)+1) )/2;</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
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> |
||
function Measure-Data |
function Measure-Data |
||
{ |
{ |
||
Line 3,278: | Line 3,278: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<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 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 3,296: | Line 3,296: | ||
</pre> |
</pre> |
||
Median only: |
Median only: |
||
< |
<syntaxhighlight lang=PowerShell> |
||
$statistics.Median |
$statistics.Median |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 3,305: | Line 3,305: | ||
=={{header|Processing}}== |
=={{header|Processing}}== |
||
< |
<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,316: | Line 3,316: | ||
float median = (nums[(nums.length - 1) / 2] + nums[nums.length / 2]) / 2.0; |
float median = (nums[(nums.length - 1) / 2] + nums[nums.length / 2]) / 2.0; |
||
return median; |
return median; |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>4.7 |
<pre>4.7 |
||
Line 3,322: | Line 3,322: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
< |
<syntaxhighlight lang=Prolog>median(L, Z) :- |
||
length(L, Length), |
length(L, Length), |
||
I is Length div 2, |
I is Length div 2, |
||
Line 3,330: | Line 3,330: | ||
maplist(nth1, Mid, [S, S], X), |
maplist(nth1, Mid, [S, S], X), |
||
sumlist(X, Y), |
sumlist(X, Y), |
||
Z is Y/2.</ |
Z is Y/2.</syntaxhighlight> |
||
=={{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 |
||
when len = # x; |
when len = # x; |
||
mid = len div 2; |
mid = len div 2; |
||
rem = len mod 2; |
rem = len mod 2; |
||
end;</ |
end;</syntaxhighlight> |
||
Output:<pre>> median [1, 3, 5]; |
Output:<pre>> median [1, 3, 5]; |
||
3.0 |
3.0 |
||
Line 3,346: | Line 3,346: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<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,380: | Line 3,380: | ||
Data.i 6 |
Data.i 6 |
||
Data.d 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 |
Data.d 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 |
||
EndDataSection</ |
EndDataSection</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang=python>def median(aray): |
||
srtd = sorted(aray) |
srtd = sorted(aray) |
||
alen = len(srtd) |
alen = len(srtd) |
||
Line 3,391: | Line 3,391: | ||
print a, median(a) |
print a, median(a) |
||
a = (4.1, 7.2, 1.7, 9.3, 4.4, 3.2) |
a = (4.1, 7.2, 1.7, 9.3, 4.4, 3.2) |
||
print a, median(a)</ |
print a, median(a)</syntaxhighlight> |
||
=={{header|R}}== |
=={{header|R}}== |
||
Line 3,397: | Line 3,397: | ||
{{trans|Octave}} |
{{trans|Octave}} |
||
< |
<syntaxhighlight lang=rsplus>omedian <- function(v) { |
||
if ( length(v) < 1 ) |
if ( length(v) < 1 ) |
||
NA |
NA |
||
Line 3,416: | Line 3,416: | ||
print(omedian(a)) |
print(omedian(a)) |
||
print(median(b)) # 4.25 |
print(median(b)) # 4.25 |
||
print(omedian(b))</ |
print(omedian(b))</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|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,432: | Line 3,432: | ||
(median '#()) ;; #f |
(median '#()) ;; #f |
||
(median '#(5 4 2 3)) ;; 7/2 |
(median '#(5 4 2 3)) ;; 7/2 |
||
(median '#(3 4 1 -8.4 7.2 4 1 1.2)) ;; 2.1</ |
(median '#(3 4 1 -8.4 7.2 4 1 1.2)) ;; 2.1</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 3,438: | Line 3,438: | ||
{{works with|Rakudo|2016.08}} |
{{works with|Rakudo|2016.08}} |
||
< |
<syntaxhighlight lang=perl6>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; |
||
}</ |
}</syntaxhighlight> |
||
Notes: |
Notes: |
||
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> |
||
=={{header|REBOL}}== |
=={{header|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,469: | Line 3,469: | ||
] |
] |
||
] |
] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ReScript}}== |
=={{header|ReScript}}== |
||
< |
<syntaxhighlight lang=ReScript>let median = (arr) => |
||
{ |
{ |
||
let float_compare = (a, b) => { |
let float_compare = (a, b) => { |
||
Line 3,495: | 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, 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]))</ |
Js.log(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
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).*/ |
||
/* ══════════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,528: | Line 3,528: | ||
n= m + 1 /*N: the next element after M. */ |
n= m + 1 /*N: the next element after M. */ |
||
if # // 2 then return @.n /*[odd?] // ◄───REXX's ÷ remainder*/ |
if # // 2 then return @.n /*[odd?] // ◄───REXX's ÷ remainder*/ |
||
return (@.m + @.n) / 2 /*process an even─element vector. */</ |
return (@.m + @.n) / 2 /*process an even─element vector. */</syntaxhighlight> |
||
{{out|output}} |
{{out|output}} |
||
<pre> |
<pre> |
||
Line 3,545: | Line 3,545: | ||
=={{header|Ring}}== |
=={{header|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,555: | Line 3,555: | ||
return (srtd[alen/2] + srtd[alen/2 + 1]) / 2.0 |
return (srtd[alen/2] + srtd[alen/2 + 1]) / 2.0 |
||
else return srtd[ceil(alen/2)] ok |
else return srtd[ceil(alen/2)] ok |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<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,571: | Line 3,571: | ||
p median([5,3,4]) # => 4 |
p median([5,3,4]) # => 4 |
||
p median([5,4,2,3]) # => 3.5 |
p median([5,4,2,3]) # => 3.5 |
||
p median([3,4,1,-8.4,7.2,4,1,1.2]) # => 2.1</ |
p median([3,4,1,-8.4,7.2,4,1,1.2]) # => 2.1</syntaxhighlight> |
||
Alternately: |
Alternately: |
||
< |
<syntaxhighlight lang=ruby>def median(aray) |
||
srtd = aray.sort |
srtd = aray.sort |
||
alen = srtd.length |
alen = srtd.length |
||
(srtd[(alen-1)/2] + srtd[alen/2]) / 2.0 |
(srtd[(alen-1)/2] + srtd[alen/2]) / 2.0 |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<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,610: | Line 3,610: | ||
print " Median :";median;chr$(9);" Values:";a$ |
print " Median :";median;chr$(9);" Values:";a$ |
||
RETURN</ |
RETURN</syntaxhighlight>Output: |
||
<pre>Median :4.4 Values:4.1,5.6,7.2,1.7,9.3,4.4,3.2 |
<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 |
Median :4.25 Values:4.1,7.2,1.7,9.3,4.4,3.2 |
||
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 { |
||
// 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,636: | Line 3,636: | ||
let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.]; |
let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.]; |
||
println!("{:?}", median(nums)) |
println!("{:?}", median(nums)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
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]) = { |
||
import n._ |
import n._ |
||
val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2) |
val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2) |
||
if (s.size % 2 == 0) (lower.last + upper.head) / fromInt(2) else upper.head |
if (s.size % 2 == 0) (lower.last + upper.head) / fromInt(2) else upper.head |
||
}</ |
}</syntaxhighlight> |
||
This isn't really optimal. The methods <tt>splitAt</tt> and <tt>last</tt> are O(n/2) |
This isn't really optimal. The methods <tt>splitAt</tt> and <tt>last</tt> are O(n/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) |
||
(* (+ (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))</ |
(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) |
||
(* (+ (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))</ |
(list-ref (sort l less?) (round (/ (length l) 2)))) 0.5))</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i"; |
||
include "float.s7i"; |
include "float.s7i"; |
||
Line 3,694: | Line 3,694: | ||
writeln("flist1 median is " <& median(flist1) digits 2 lpad 7); # 4.85 |
writeln("flist1 median is " <& median(flist1) digits 2 lpad 7); # 4.85 |
||
writeln("flist2 median is " <& median(flist2) digits 2 lpad 7); # 4.60 |
writeln("flist2 median is " <& median(flist2) digits 2 lpad 7); # 4.60 |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{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] |
||
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,712: | Line 3,712: | ||
return the middle item of list |
return the middle item of list |
||
end if |
end if |
||
end customMedian</ |
end customMedian</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang=sensetalk>4.4 |
||
5 |
5 |
||
4.4 |
4.4 |
||
5</ |
5</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang=ruby>func median(arry) { |
||
var srtd = arry.sort; |
var srtd = arry.sort; |
||
var alen = srtd.length; |
var alen = srtd.length; |
||
srtd[(alen-1)/2]+srtd[alen/2] / 2; |
srtd[(alen-1)/2]+srtd[alen/2] / 2; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang=slate>s@(Sequence traits) median |
||
[ |
[ |
||
s isEmpty |
s isEmpty |
||
Line 3,737: | Line 3,737: | ||
ifTrue: [(sorted middle + (sorted at: sorted indexMiddle - 1)) / 2] |
ifTrue: [(sorted middle + (sorted at: sorted indexMiddle - 1)) / 2] |
||
ifFalse: [sorted middle]] |
ifFalse: [sorted middle]] |
||
].</ |
].</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.</ |
inform: { 4.1 . 7.2 . 1.7 . 9.3 . 4.4 . 3.2 } median.</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
{{works with|GNU Smalltalk}} |
{{works with|GNU Smalltalk}} |
||
< |
<syntaxhighlight lang=smalltalk>OrderedCollection extend [ |
||
median [ |
median [ |
||
self size = 0 |
self size = 0 |
||
Line 3,757: | Line 3,757: | ||
ifTrue: [ ^nil ] |
ifTrue: [ ^nil ] |
||
] |
] |
||
].</ |
].</syntaxhighlight> |
||
< |
<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 |
||
median displayNl.</ |
median displayNl.</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
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 |
||
gen x=rbeta(0.2,1.3) |
gen x=rbeta(0.2,1.3) |
||
quietly summarize x, detail |
quietly summarize x, detail |
||
display r(p50)</ |
display r(p50)</syntaxhighlight> |
||
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 |
||
sort `1' |
sort `1' |
||
if mod(_N,2)==0 { |
if mod(_N,2)==0 { |
||
Line 3,785: | Line 3,785: | ||
calcmedian x |
calcmedian x |
||
display r(p50)</ |
display r(p50)</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<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,803: | Line 3,803: | ||
} |
} |
||
puts [median 3.0 4.0 1.0 -8.4 7.2 4.0 1.0 1.2]; # --> 2.1</ |
puts [median 3.0 4.0 1.0 -8.4 7.2 4.0 1.0 1.2]; # --> 2.1</syntaxhighlight> |
||
=={{header|TI-83 BASIC}}== |
=={{header|TI-83 BASIC}}== |
||
Using the built-in function: |
Using the built-in function: |
||
< |
<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> |
||
=={{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 |
||
#import flo |
#import flo |
||
median = fleq-<; @K30K31X eql?\~&rh div\2.+ plus@lzPrhPX</ |
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 |
||
examples = |
examples = |
||
Line 3,827: | Line 3,827: | ||
median~~ ( |
median~~ ( |
||
<9.3,-2.0,4.0,7.3,8.1,4.1,-6.3,4.2,-1.0,-8.4>, |
<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>)</ |
<8.3,-3.6,5.7,2.3,9.3,5.4,-2.3,6.3,9.9>)</syntaxhighlight> |
||
output: |
output: |
||
<pre> |
<pre> |
||
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) { |
||
double a = *(double*) a_ref; |
double a = *(double*) a_ref; |
||
double b = *(double*) b_ref; |
double b = *(double*) b_ref; |
||
Line 3,853: | Line 3,853: | ||
double[] array2 = {2, 4, 6, 1, 7, 3, 5, 8}; |
double[] array2 = {2, 4, 6, 1, 7, 3, 5, 8}; |
||
print(@"$(median(array1)) $(median(array2))\n"); |
print(@"$(median(array1)) $(median(array2))\n"); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
{{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 |
||
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,875: | Line 3,875: | ||
s = [{4, 2, 3, 5, 1, 6}] |
s = [{4, 2, 3, 5, 1, 6}] |
||
Debug.Print medianq(s) |
Debug.Print medianq(s) |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre> 3,5 </pre> |
<pre> 3,5 </pre> |
||
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) |
||
EOF Goto_Line(Cur_Line/2) |
EOF Goto_Line(Cur_Line/2) |
||
Reg_Copy(10, 1)</ |
Reg_Copy(10, 1)</syntaxhighlight> |
||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<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,903: | Line 3,903: | ||
} |
} |
||
return m |
return m |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,915: | Line 3,915: | ||
println(stats.median<int>([1, 1, 3, 4])) // prints 2 |
println(stats.median<int>([1, 1, 3, 4])) // prints 2 |
||
println(stats.median<int>([1, 1, 3, 4, 5])) // prints 3 |
println(stats.median<int>([1, 1, 3, 4, 5])) // prints 3 |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Wortel}}== |
=={{header|Wortel}}== |
||
< |
<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,931: | Line 3,931: | ||
!med2 [4 5 2 1] |
!med2 [4 5 2 1] |
||
]] |
]] |
||
}</ |
}</syntaxhighlight> |
||
Returns: <pre>[2 3 2 3]</pre> |
Returns: <pre>[2 3 2 3]</pre> |
||
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 |
||
import "/math" for Nums |
import "/math" for Nums |
||
import "/queue" for PriorityQueue |
import "/queue" for PriorityQueue |
||
Line 3,969: | Line 3,969: | ||
} |
} |
||
System.print() |
System.print() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,984: | Line 3,984: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
{{trans|Lua}} |
{{trans|Lua}} |
||
< |
<syntaxhighlight lang=Yabasic>sub floor(x) |
||
return int(x + .05) |
return int(x + .05) |
||
end sub |
end sub |
||
Line 4,040: | 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, 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 |
print median("4.1, 7.2, 1.7, 9.3, 4.4, 3.2") // 4.25 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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; |
||
fcn median(xs){ |
fcn median(xs){ |
||
Line 4,050: | Line 4,050: | ||
if (n.isOdd) return(quickSelect(xs,n/2)); |
if (n.isOdd) return(quickSelect(xs,n/2)); |
||
( quickSelect(xs,n/2-1) + quickSelect(xs,n/2) )/2; |
( 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</ |
median(T( 5.1, 2.6, 8.8, 4.6, 4.1 )); //-->4.6</syntaxhighlight> |
||
=={{header|Zoea}}== |
=={{header|Zoea}}== |
||
< |
<syntaxhighlight lang=Zoea> |
||
program: median |
program: median |
||
case: 1 |
case: 1 |
||
Line 4,066: | Line 4,066: | ||
input: [2,5,6,8] |
input: [2,5,6,8] |
||
output: 5.5 |
output: 5.5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Zoea Visual}}== |
=={{header|Zoea Visual}}== |
||
Line 4,072: | Line 4,072: | ||
=={{header|zonnon}}== |
=={{header|zonnon}}== |
||
< |
<syntaxhighlight lang=zonnon> |
||
module Averages; |
module Averages; |
||
Line 4,142: | Line 4,142: | ||
writeln(Median(ary):10:2) |
writeln(Median(ary):10:2) |
||
end Averages. |
end Averages. |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
4 |
4 |