How to resolve the algorithm Averages/Median step by step in the Action! programming language
How to resolve the algorithm Averages/Median step by step in the Action! programming language
Table of Contents
Problem Statement
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. Quickselect_algorithm
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Averages/Median step by step in the Action! programming language
Source code in the action! programming language
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
You may also check:How to resolve the algorithm Sequence of primes by trial division step by step in the F# programming language
You may also check:How to resolve the algorithm Sum and product of an array step by step in the Lingo programming language
You may also check:How to resolve the algorithm Yin and yang step by step in the Mathematica / Wolfram Language programming language
You may also check:How to resolve the algorithm Function definition step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Hailstone sequence step by step in the Kotlin programming language