Task[edit]
Write a program to find the   median   value of a vector of floating-point numbers.

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

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

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

See also
Quickselect_algorithm

Tasks for calculating statistical measures



in one go
moving (sliding window)
moving (cumulative)

Mean
Arithmetic

Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means


Averages/Simple moving average




Geometric

Averages/Pythagorean means




Harmonic

Averages/Pythagorean means




Quadratic

Averages/Root mean square




Circular

Averages/Mean angle
Averages/Mean time of day




Median

Averages/Median




Mode

Averages/Mode




Standard deviation

Statistics/Basic



Cumulative standard deviation




INCLUDE "H6:REALMATH.ACT"
 
DEFINE PTR="CARD"
 
PROC Sort(PTR ARRAY a INT count)
  INT i,j,minpos
  REAL POINTER tmp
 
  FOR i=0 TO count-2
  DO
    minpos=i
    FOR j=i+1 TO count-1
    DO
      IF RealGreaterOrEqual(a(minpos),a(j)) THEN
        minpos=j
      FI
    OD
 
    IF minpos#i THEN
      tmp=a(i)
      a(i)=a(minpos)
      a(minpos)=tmp
    FI
  OD
RETURN
 
PROC Median(PTR ARRAY a INT count REAL POINTER res)
  IF count=0 THEN Break() FI
  Sort(a,count)
  IF (count&1)=0 THEN
    RealAdd(a(count RSH 1-1),a(count RSH 1),res)
    RealMult(res,half,res)
  ELSE
    RealAssign(a(count RSH 1),res)
  FI
RETURN
 
PROC Test(PTR ARRAY a INT count)
  INT i
  REAL res
 
  FOR i=0 TO count-1
  DO
    PrintR(a(i)) Put(32)
  OD
  Median(a,count,res)
  Print("-> ")
  PrintRE(res)
RETURN
 
PROC Main()
  PTR ARRAY a(8)
  REAL r1,r2,r3,r4,r5,r6,r7,r8
  BYTE i
 
  Put(125) PutE() ;clear the screen
  MathInit()
  ValR("3.2",r1)  ValR("-4.1",r2)
  ValR("0.6",r3)  ValR("9.8",r4)
  ValR("5.1",r5)  ValR("-1.4",r6)
  ValR("0.3",r7) ValR("2.2",r8)
  FOR i=1 TO 8
  DO
    a(0)=r1 a(1)=r2 a(2)=r3 a(3)=r4
    a(4)=r5 a(5)=r6 a(6)=r7 a(7)=r8
    Test(a,i)
  OD
RETURN